You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript将图片转换为Base64字符串时如何减小生成字符串的体积

减小图片转Base64后体积的实现方法

Base64编码本身存在固定的体积膨胀特性:编码后数据量比原始二进制文件大约33%,这是编码规则决定的,无法从编码环节优化。想要减小最终生成的Base64字符串体积,核心方案是先对原始图片做压缩处理,再将压缩后的图片转为Base64格式。

你可以通过Canvas API实现前端图片压缩,修改后的完整实现代码如下:

<input id="inputFileToLoad" type="file" accept="image/*" onchange="encodeImageFileAsURL();"/>
<div id="imgTest"></div>

<script type='text/javascript'>
  // 图片压缩方法
  function compressImage(file, maxWidth = 1200, maxHeight = 1200, quality = 0.7) {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        const img = new Image();
        img.src = e.target.result;
        img.onload = () => {
          // 计算等比缩放后的宽高
          let width = img.width;
          let height = img.height;
          if (width > maxWidth) {
            height *= maxWidth / width;
            width = maxWidth;
          }
          if (height > maxHeight) {
            width *= maxHeight / height;
            height = maxHeight;
          }
          // 绘制到canvas
          const canvas = document.createElement('canvas');
          canvas.width = width;
          canvas.height = height;
          const ctx = canvas.getContext('2d');
          ctx.drawImage(img, 0, 0, width, height);
          // 转为base64,优先用webp格式压缩率更高
          const base64 = canvas.toDataURL('image/webp', quality);
          resolve(base64);
        }
      }
      reader.readAsDataURL(file);
    })
  }

  async function encodeImageFileAsURL(){
    const filesSelected = document.getElementById("inputFileToLoad").files;
    const fileSize = filesSelected[0].size;
    if(fileSize < 10000000){
      if (filesSelected.length > 0){
        const fileToLoad = filesSelected[0];
        // 先压缩再拿base64
        const compressedBase64 = await compressImage(fileToLoad);
        const newImage = document.createElement('img');
        newImage.src = compressedBase64;

        document.getElementById("imgTest").innerHTML = newImage.outerHTML;
        alert("Converted Base64 version is " + compressedBase64);
      }
    } else {
      alert("File exceeded"); 
    }
  }
</script>

压缩参数调整说明

  • 最大宽高限制:可修改compressImage方法的maxWidth、maxHeight参数,对超出尺寸的大图片做等比缩放,大幅降低高分辨率图片的体积
  • 输出质量:可修改quality参数(取值范围0-1),数值越低压缩率越高,建议取值0.5-0.8区间,可兼顾画质和压缩效果
  • 输出格式:如果需要兼容旧浏览器,可将canvas.toDataURL的第一个参数改为image/jpeg,兼容性更好但压缩率略低于webp

内容的提问来源于stack exchange,提问作者mucellakaya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:36:08