JS image compression (applicable to both PC and mobile terminals)

From , 2 Years ago, written in JavaScript, viewed 93 times.
URL https://pastebin.vip/view/a9df2255
  1. /**
  2.  * 图片压缩,默认同比例压缩
  3.  * @param {Object} path    
  4.  *         pc端传入的路径可以为相对路径,但是在移动端上必须传入的路径是照相图片储存的绝对路径
  5.  * @param {Object} obj
  6.  *         obj 对象 有 width, height, quality(0-1)
  7.  * @param {Object} callback
  8.  *         回调函数有一个参数,base64的字符串数据
  9.  */
  10. function dealImage(path, obj, callback){
  11.     var img = new Image();
  12.     img.src = path;
  13.     img.onload = function(){
  14.         var that = this;
  15.         // 默认按比例压缩
  16.         var w = that.width,
  17.             h = that.height,
  18.             scale = w / h;
  19.             w = obj.width || w;
  20.             h = obj.height || (w / scale);
  21.         var quality = 0.7;        // 默认图片质量为0.7
  22.        
  23.         //生成canvas
  24.         var canvas = document.createElement('canvas');
  25.         var ctx = canvas.getContext('2d');
  26.        
  27.         // 创建属性节点
  28.         var anw = document.createAttribute("width");
  29.         anw.nodeValue = w;
  30.         var anh = document.createAttribute("height");
  31.         anh.nodeValue = h;
  32.         canvas.setAttributeNode(anw);
  33.         canvas.setAttributeNode(anh);
  34.              
  35.         ctx.drawImage(that, 0, 0, w, h);
  36.         // 图像质量
  37.         if(obj.quality && obj.quality <= 1 && obj.quality > 0){
  38.             quality = obj.quality;
  39.         }
  40.         // quality值越小,所绘制出的图像越模糊
  41.         var base64 = canvas.toDataURL('image/jpeg', quality );
  42.         // 回调函数返回base64的值
  43.         callback(base64);
  44.     }
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52. 如果可以试着测试一下压缩后的图片大小:
  53.  
  54.  
  55.  
  56.  
  57. =====================================================================================
  58. 当然返回的是一个base64的一个字符串;
  59. // 调用函数处理图片                 dealImage("路径", {// 注意:在pc端可以用绝对路径或相对路径,移动端最好用绝对路径(因为用take photo后的图片路径,我没有试成功(如果有人试成功了可以分享一下经验)) width : 200}, function(base){//直接将获取到的base64的字符串,放到一个image标签中就可看到测试后的压缩之后的样式图了 document.getElementById("transform").src = base; console.log("压缩后:" + base.length / 1024 + " " + base);    })
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  

Reply to "JS image compression (applicable to both PC and mobile terminals)"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website