js前端图片压缩功能(canvas)

前段时间准备换工作,去面试,被问到有没有自己实现过图片压缩,很尴尬,确实没有。于是,刚好有时间,就自己简单记录一下

html:

<input type="file" accept="image/*" @change="changeFile($event)" />

js:

changeFile(e) {
    const img = new Image();
    const reader = new FileReader();
    let file = e.target.files[0];
    //缩放图片需要的canvas
    let canvas = document.createElement('canvas');
    let context = canvas.getContext('2d');
    //判断选择的图片是否图片
    if (e.type.indexOf('image') == 0) {
        reader.readAsDataURL(file);
    }
    //文件base64化,以便获知图片原始尺寸
    reader.onload = function(even) {
        img.src = even.target.result;
    };
    //base64地址图片加载完毕后
    img.onload = function() {
        //图片原始尺寸
        let originWidth = this.width;
        let originHeight = this.height;
        console.log(originWidth, originHeight);
        //最大尺寸限制
        let maxWidth = 400;
        let maxHeight = 400;
        //目标尺寸
        let targetWidth = originWidth;
        let targetHeight = originHeight;
        //图片尺寸超过400*400的限制
        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对图片进行缩放
        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) {
            //图片ajax上传
            const formData = new FormData();
            formData.append('file', blob);
            //调用上传图片接口
            //axios.post('http://xxx.com/api',formData);
            //清除内容
            //e.target.value = '';
        }, file.type || 'image/png');
    };
},

 

还有很多可以优化的地方,比如

1、将文件file转换成img可以提取个方法

2、图片压缩可以提取个方法,然后限制大小用传参的方式

等等。。。

 

posted @ 2021-05-06 11:00  超哥20  阅读(295)  评论(0编辑  收藏  举报