首页 > 技术文章 > jquery 压缩图片、等比缩放

Sherries 2021-04-08 13:58 原文


/* 压缩图片 */
<div class="compress" >
  <img id="web" src=""/>
</div>

$("#web").attr('src',base64)

// 方法一:jquery自动调整图片大小、缩放
$('.compress img').each(function(){
  var x = 500; //填入目标图片宽度
  var y = 300; //填入目标图片高度
  var w=$(this).width(), h=$(this).height();//获取图片宽度、高度

  if (w > x) { //图片宽度大于目标宽度时
    var w_original=w, h_original=h;
    h = h * (x / w); //根据目标宽度按比例算出高度
    w = x; //宽度等于预定宽度
    if (h < y) { //如果按比例缩小后的高度小于预定高度时
      w = w_original * (y / h_original); //按目标高度重新计算宽度
      h = y; //高度等于预定高度
    }
  }
  $(this).attr({width:w,height:h});
});

//或

$(window).bind("load", function() {
  $('#product_cat_list img').each(function() {
    var maxWidth = 120;
    var maxHeight = 120;
    var ratio = 0;
    var width = $(this).width();
    var height = $(this).height();
 
    if(width > maxWidth){
      ratio = maxWidth / width;
      $(this).css("width", maxWidth);
      $(this).css("height", height * ratio);
      height = height * ratio;
    }
    var width = $(this).width();
    var height = $(this).height();
    if(height > maxHeight){
      ratio = maxHeight / height;
      $(this).css("height", maxHeight);
      $(this).css("width", width * ratio);
      width = width * ratio;
    }
  });
  //$("#contentpage img").show();
});


//方法二:等比缩放图片自适应页面布局

var w = $(".compress").width();//容器宽度
$(".compress img").each(function(){//如果有很多图片,我们可以使用each()遍历
    var img_w = $(this).width();//图片宽度
    var img_h = $(this).height();//图片高度
    console.log(img_w)
    if(img_w>w){//如果图片宽度超出容器宽度--要撑破了
        var height = (w*img_h)/img_w; //高度等比缩放
        $(this).css({"width":w,"height":height});//设置缩放后的宽度和高度
    }
});


//方法三:

<input type="file" id="picFile" onchange="readFile(this)"/>
<img style="" id="img" src="" alt="" />

function readFile(obj){
    var file = obj.files[0];  
    //判断类型是不是图片
    if(!/image\/\w+/.test(file.type)){
      alert("请确保文件为图像类型");
      return false;
    }
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(e){
        dealImage(this.result,{width:200},function(base){
            document.getElementById('img').setAttribute('src',base)
        });
    }
}
 
/* 图片压缩,默认同比例压缩
 * @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
       
       var canvas = document.createElement('canvas');//生成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('image/jpeg', quality );
       // 回调函数返回base64的值
       callback(base64);
   }
}


//方法四:js实现纯前端压缩图片
<input id='file' type="file">

  var eleFile = document.querySelector('#file')
  var file;
  var render = new FileReader(), img = new Image();
  render.onload = function(e) {
   img.src = e.target.result
  }
  // 获取图片文件
  eleFile.addEventListener('change', function(e) {
   file = e.target.files[0];
   if(file.type.indexOf('image') === 0) {
    //读取文件,并返回一个URL格式的Base64字符串
    render.readAsDataURL(file)
   }
  })
 
  //使用canvas把图片画出来
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');
 
  img.onload = function() {
 
   //原始尺寸
   var originWidth = this.width;
   var originHeight = this.height;
 
   //最大尺寸限制
   var maxWidth = 200, maxHeight = 200
 
   // 目标尺寸
   var targetWidth = originWidth, targetHeight = originHeight;
 
   //当原始尺寸大于200*200时候
   if(originWidth > maxWidth || originHeight > maxHeight) {
    if(originWidth / originHeight > maxWidth / maxHeight) {
     //更宽
     targetWidth = maxWidth;
     targetHeight = Math.round(maxWidth * (originHeight / originWidth))
    }else {
     targetHeight = maxHeight;
     targetWidth = Math.round(maxHeight * (originWidth / originHeight))
    }
   }
 
   //画图
   canvas.width = targetWidth;
   canvas.height = targetHeight;
   //清除画布
   context.clearRect(0,0,targetWidth, targetHeight)
   //图片压缩
   context.drawImage(img, 0, 0, targetWidth, targetHeight);
   //canvas 转为blob并上传
   canvas.toBlob(function(blob) {
    try {
     var xhr = new XMLHttpRequest();
     xhr.onreadystatechange = function() {{
      if(xhr.status == 200) {
 
      }
     }}
     //开始上传
     xhr.open('POST','upload.php', true);
     xhr.send(blob)
    } catch (error) {
        console.log(error)
    }
   }, file.type || 'image/png')
   //在页面预览原图片
   var div1 = document.createElement('div')
   div1.innerText = '原图:'
   document.body.appendChild(div1)
   document.body.appendChild(img)
   //canvas预览
   var div2 = document.createElement('div')
   div2.innerText = 'canvas图:'
   document.body.appendChild(div2)
   document.body.appendChild(canvas)
  }

//jquery获取img实际尺寸的方法
$(function(){
  var imgSrc = $("#image").attr("src");
  getImageWidth(imgSrc,function(w,h){
    console.log({width:w,height:h});
  });
});
 
function getImageWidth(url,callback){
  var img = new Image();
  img.src = url;
 
  // 如果图片被缓存,则直接返回缓存数据
  if(img.complete){
    callback(img.width, img.height);
  }else{
      // 完全加载完毕的事件
    img.onload = function(){
        callback(img.width, img.height);
    }
  }
}
 

推荐阅读