首页 > 编程语言 >碎片化学习前端之JavaScript(JS 压缩图片)

碎片化学习前端之JavaScript(JS 压缩图片)

时间:2023-06-15 17:13:09浏览次数:52  
标签:canvas img JS 压缩 JavaScript height width file 碎片

前言

图片压缩是前端开发中常见的需求,目前前端主流的解决方案有:Canvas 手动实现压缩以及第三方库压缩两种方案。

Canvas 手动实现压缩

Canvas 实现压缩主要原理是:将图片绘制到 canvas 上,然后通过调整 canvas 的宽高来实现压缩。

function compressImage(file, maxWidth, maxHeight, quality) {
  return new Promise((resolve, reject) => {
  
    const reader = new FileReader();
    reader.readAsDataURL(file);
    
    reader.onload = function(event) {
	
      const img = new Image();
      img.src = event.target.result;
      // 图片加载完成以后再进行 canvas 绘制
      img.onload = function() {

        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        let width = img.width;
        let height = img.height;
        if (width > height) {
          if (width > maxWidth) {
            height *= maxWidth / width;
            width = maxWidth;
          }
        } else {
          if (height > maxHeight) {
            width *= maxHeight / height;
            height = maxHeight;
          }
        }
        canvas.width = width;
        canvas.height = height;

        ctx.drawImage(img, 0, 0, width, height);

        canvas.toBlob(function(blob) {
          resolve(blob);
        }, file.type || 'image/png', quality); // quality 为图片质量
      };
    };
  });
}

第三方库压缩

第三方库可以使用 compressorjs 来实现。

import Compressor from 'compressorjs';

document.getElementById('file').addEventListener('change', (e) => {
  const file = e.target.files[0];

  if (!file) {
    return;
  }

  new Compressor(file, {
    quality: 0.6,
    success(result) {},
    error(err) {},
  });

});

后记

什么有损和无损压缩,咱就不考虑了,超纲了,容易掉头发,要求高了找 UI !哈哈哈哈~嗝

标签:canvas,img,JS,压缩,JavaScript,height,width,file,碎片
From: https://www.cnblogs.com/huangminghua/p/17483377.html

相关文章

  • Compile Unity jslib in command
    CompileUnityjslibincommand(JinQing’sColumn,May.,2023)MyUnityprojecthasajslibfile,whichhasmanysyntaxerrors.ButUnitydoesnotreportthesejsliberrorslikecsfiles,untiltheWebGLbuildfailswithaerrorlikethis:Failedprocessstd......
  • Linux安装nodejs
    cd/opt/softwgethttps://cdn.npmmirror.com/binaries/node/v16.15.1/node-v16.15.1-linux-x64.tar.xztar-xvfnode-v16.15.1-linux-x64.tar.xzmvnode-v16.15.1-linux-x64nodejs-v16.15#建立软连接ln-s/opt/soft/nodejs-v16.15/bin/node/usr/bin/nodeln-s/o......
  • npm publish 发包报错npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/
    如果出现在发布的时候报这个错,说明你在package.json中登记的name已近被采用了。重名了,所以你得换一个。我们在发布一个包之前,最好拿着这个登记的name去搜一下,如果已近有了,那就要换一个。......
  • js判断开始时间是否小于结束时间(时分 格式)
    shifen(shi,fen){//分割开始时间的时letkaiShi=shi.split(":")[0];//分割开始时间的分letkaiFen=shi.split(":")[1];//分割结束时间的时letjieShi=fen.split(":")[0];......
  • js判断时间是否存在重叠(多个时间段)
    Fn(dateAr){for(letkindateAr){if(!this.judege(k)){returnfalse}}returntrue},judege(idx){letdateAr=this.sellerTimeJson......
  • JavaScript开发工具-WebStorm 2023 mac/win版
    WebStorm是一款由JetBrains开发的JavaScript开发工具,是专为JavaScript开发者设计的集成开发环境(IDE)。它提供了强大的功能和工具,能够帮助开发者更高效地编写、调试和维护JavaScript代码。→→↓↓载WebStorm2023mac/win版 WebStorm拥有一套丰富的功能,使得它成为JavaScript开......
  • [从jQuery看JavaScript]-匿名函数与闭包(Anonymous Function and Closure)
    jQuery片段:1.(function(){2.//这里忽略jQuery所有实现3.})();当一个匿名函数被括起来,然后再在后面加一个括号,这个匿名函数就能立即运行起来!真神奇哦!嘿嘿!胡闹到此为止。在这一节,我们碰到的jQuery片段是一组立即运行的匿名函数。而这种用法在论坛上也曾引起过激辩......
  • [从jQuery看JavaScript]-数据类型和对象(Type and Object)(一)
    jQuery片段:1.var2.//Willspeedupreferencestowindow,andallowsmungingitsname.3.window=this,4.//Willspeedupreferencestoundefined,andallowsmungingitsname.5.undefined,6.//MapoverjQueryincas......
  • JS 保留小数 又一方法
    对于X进行保留两位小数的处理,则可以使用Math.round(X*100)/100进行处理。 在JavaScript中,对数值进行四舍五入操作的场景还有以下几种:向上取整:ceil向下取整:floor四舍五入:round固定精度:toFixed固定长度:toPrecision取整:parseInt、位运算 ......
  • JavaScript中将字符串转换为数字的七种方法总结 乘以数字: str = '2344'; console.lo
    JavaScript中将字符串转换为数字的七种方法总结乘以数字:str='2344';console.log(str*1)//expectedresult:2344https://www.jb51.net/article/261613.htm+目录1.使用parseInt()2.使用Number()3.使用一元运算符(+)4.使用parseFloat()5.使用Math.floor()6.乘......