The cycled pictures are converted to base64 compression

Most of the time we need to compress a File object and then turn it into a File object and pass it to the remote image server;
sometimes we also need to compress a base64 string and then turn it into a base64 string and pass it to the remote database;
sometimes it It may also be a canvas, or an Image object, or directly the url address of a picture, we need to compress and upload them to the remote.

Here we introduce the compressed display of a picture address. The principle is to parse the url address through js, and redraw the parsed picture on the dom element

<img :id="'img'+index" src=""  v-for="(item,index) in list" :key="index" />



// 压缩图片的方法
function canvasDataURL(path, obj, callback){
    
    
    var img = new Image();
    img.src = path;
    img.setAttribute("crossOrigin",'Anonymous')
    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('image/jpeg', quality);
        // 回调函数返回base64的值
        callback(base64);
    }
}

//后端返回的图片列表
if(res.data.code===200) {
    
    
  this.list= res.data.data
  let url
  this.list.forEach((item,index) => {
    
    
    url = 'http://baidu.com'+item.imgurl
    canvasDataURL(url,{
    
    quality:0.1},function(base64){
    
    
        // $('#cunImg').val(base64)
        // $('#showImg').attr('src',base64)
        document.getElementById("img"+index).setAttribute("src", base64)

    })
  });
}

Guess you like

Origin blog.csdn.net/weixin_43045869/article/details/127439325