JavaScript如何将上传的base64图片调整为250x250尺寸后传入输入框
图片上传前固定缩放为250x250的实现方案
核心基于Canvas API实现图片尺寸调整,无需引入第三方依赖,修改后的完整代码如下:
function sendPhoto() { if (this.files && this.files[0]) { // 前置校验文件类型,无需读取文件内容即可判断,性能更优 const permittedFiles = ['image/png', 'image/jpeg', 'image/bmp']; if (!permittedFiles.includes(this.files[0].type)) { $('body').overhang({ type: 'error', message: 'This is not an image file.', }); document.getElementById('uploadFoto').value = ''; return; } const FR = new FileReader(); FR.addEventListener('load', function (e) { const originBase64 = e.target.result; // 创建临时图片对象加载原图 const tempImg = new Image(); tempImg.src = originBase64; tempImg.onload = function() { const targetSize = 250; // 创建画布用于重绘缩放 const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width = targetSize; canvas.height = targetSize; // 方案1:保持原图比例居中裁剪,无拉伸变形,适合头像等场景 const originWidth = this.width; const originHeight = this.height; const scale = Math.max(targetSize / originWidth, targetSize / originHeight); const drawWidth = originWidth * scale; const drawHeight = originHeight * scale; const offsetX = (targetSize - drawWidth) / 2; const offsetY = (targetSize - drawHeight) / 2; ctx.drawImage(this, offsetX, offsetY, drawWidth, drawHeight); // 方案2:直接拉伸适配250x250,比例不一致时会变形,不需要方案1可注释上面代码启用下方代码 // ctx.drawImage(this, 0, 0, targetSize, targetSize); // 导出缩放后的base64,第二个参数为jpeg质量(0-1),可根据需求调整文件大小 const resizedBase64 = canvas.toDataURL(tempImg.src.split(',')[0].match(/:(.*?);/)[1], 0.9); // 后续逻辑使用缩放后的base64即可 document.getElementById('sendedPhoto').src = resizedBase64; document.getElementById('btnPhoto').style.display = ''; } }); FR.readAsDataURL(this.files[0]); } }
关键逻辑说明
- 前置类型校验:优化了原代码中需要读取base64才能判断类型的逻辑,直接通过File对象的
type属性判断,避免无效的文件读取操作 - 图片加载:通过临时
Image对象加载原图,拿到原图的宽高参数用于计算缩放比例 - 缩放模式:提供两种缩放选择,可根据业务场景切换
- 导出配置:
toDataURL方法的第二个参数可调整jpeg格式的导出质量,数值越高画质越好、文件体积越大,可根据需求调整 - 兼容性:支持所有主流移动端、桌面端浏览器,无额外依赖
内容的提问来源于stack exchange,提问作者Pedro Miguez
相关产品推荐
相关产品推荐

