Home > Web Front-end > JS Tutorial > JavaScript code to implement image compression

JavaScript code to implement image compression

不言
Release: 2018-08-22 11:27:28
Original
1795 people have browsed it

The content of this article is about the JavaScript code for image compression. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Without further ado, let’s go straight to the code. What is returned is a base64 string

/**
 * 图片压缩,默认同比例压缩
 * @param {Object} path 
 *   pc端传入的路径可以为相对路径,但是在移动端上必须传入的路径是照相图片储存的绝对路径
 * @param {Object} obj
 *   obj 对象 有 width, height, quality(0-1)
 * @param {Object} callback
 *   回调函数有一个参数,base64的字符串数据
 */
function dealImage(path, obj, callback){
 var img = new Image();
 img.src = path;
 img.onload = function(){
  var that = this;
  // 默认按比例压缩
  var w = that.width,
   h = that.height,
   scale = w / h;
   w = obj.width || w;
   h = obj.height || (w / scale);
  var quality = 0.7;  // 默认图片质量为0.7
  //生成canvas
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  // 创建属性节点
  var anw = document.createAttribute("width");
  anw.nodeValue = w;
  var anh = document.createAttribute("height");
  anh.nodeValue = h;
  canvas.setAttributeNode(anw);
  canvas.setAttributeNode(anh); 
  ctx.drawImage(that, 0, 0, w, h);
  // 图像质量
  if(obj.quality && obj.quality <= 1 && obj.quality > 0){
   quality = obj.quality;
  }
  // quality值越小,所绘制出的图像越模糊
  var base64 = canvas.toDataURL(&#39;image/jpeg&#39;, quality );
  // 回调函数返回base64的值
  callback(base64);
 }
}
Copy after login

Calling method

// 调用函数处理图片                 
dealImage("路径", {
// 注意:在pc端可以用绝对路径或相对路径,移动端最好用绝对路径(因为用take photo后的图片路径,我没有试成功(如果有人试成功了可以分享一下经验))
 width : 200
}, function(base){
//直接将获取到的base64的字符串,放到一个image标签中就可看到测试后的压缩之后的样式图了
 document.getElementById("transform").src = base;
 console.log("压缩后:" + base.length / 1024 + " " + base);    
})
Copy after login

PS: The main idea is After obtaining the image, use H5 canvas technology to convert the image data into a base64 string, and finally transmit it to the background. The background will store the base64 string data as an image.

Related recommendations:

Javascript code sharing to realize provincial and municipal linkage

Javascript code introduction to realize binary tree

The above is the detailed content of JavaScript code to implement image compression. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template