From 835426b13339037ab19a73f3e91aee1fe97d5adc Mon Sep 17 00:00:00 2001 From: spdis Date: Thu, 27 Nov 2025 12:11:58 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=BA=86=E4=B8=8D=E6=94=AF?= =?UTF-8?q?=E6=8C=81webp=E6=A0=BC=E5=BC=8F=E7=9A=84=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- elastic/templates/elastic/upload.html | 37 +++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/elastic/templates/elastic/upload.html b/elastic/templates/elastic/upload.html index 6cc1a75..e60eb28 100644 --- a/elastic/templates/elastic/upload.html +++ b/elastic/templates/elastic/upload.html @@ -139,6 +139,32 @@ const dropArea = document.getElementById('dropArea'); let currentImageRel = ''; +async function convertToJpeg(file){ + const url = URL.createObjectURL(file); + let img; + try{ + const blob = await fetch(url).then(r=>r.blob()); + img = await createImageBitmap(blob); + }catch(e){ + img = await new Promise((resolve,reject)=>{const i=new Image();i.onload=()=>resolve(i);i.onerror=reject;i.src=url;}); + } + URL.revokeObjectURL(url); + const maxDim = 2000; + const w = img.width; + const h = img.height; + const scale = Math.min(1, maxDim/Math.max(w,h)); + const nw = Math.round(w*scale); + const nh = Math.round(h*scale); + const canvas = document.createElement('canvas'); + canvas.width = nw; + canvas.height = nh; + const ctx = canvas.getContext('2d'); + ctx.drawImage(img, 0, 0, nw, nh); + const blob = await new Promise(resolve=>canvas.toBlob(resolve,'image/jpeg',0.82)); + const name = (file.name||'image').replace(/\.[^/.]+$/, '') + '.jpg'; + return new File([blob], name, {type:'image/jpeg'}); +} + // 拖拽上传功能 ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { dropArea.addEventListener(eventName, preventDefaults, false); @@ -289,8 +315,15 @@ uploadForm.addEventListener('submit', async (e) => { return; } + let jpegFile = file; + try { + jpegFile = await convertToJpeg(file); + preview.src = URL.createObjectURL(jpegFile); + } catch (_) { + jpegFile = file; + } const formData = new FormData(); - formData.append('file', file); + formData.append('file', jpegFile); try { const resp = await fetch('/elastic/upload/', { @@ -381,4 +414,4 @@ document.getElementById('logoutBtn').addEventListener('click', async () => { }); - \ No newline at end of file +