前端如何压缩图片?压缩图片函数封装

前端压缩图片很常见,上传头像图片啥的,都需要前端压一下再给后端,于是乎就封装成函数,全局引入一下,随时随用。

  • 压缩图片函数
let ImgFile = function (e, maxWidth, maxHeight) {
    return new Promise(function (resolve, reject) {
        var file = e.target.files[0];
        if (file.type.indexOf("image") === 0) {
            var reader = new FileReader(),
                img = new Image();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                img.src = e.target.result;
            };
            img.onload = async function () {
                var canvas = document.createElement("canvas");
                var context = canvas.getContext("2d");
                // 图片原始尺寸
                var originWidth = this.width;
                var originHeight = this.height;
                // 目标尺寸
                var targetWidth = originWidth,
                    targetHeight = originHeight;
                // 如果图片尺寸超过限制的最大尺寸
                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);
                let dataurl = canvas.toDataURL("image/jpg", 0.92);
                let filename = file.name;
                let arr = dataurl.split(",");
                let mime = arr[0].match(/:(.*?);/)[1];
                let bstr = atob(arr[1]);
                let n = bstr.length;
                let u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                resolve(await new File([u8arr], filename, { type: mime }));
            };
        } else {
            return "请上传图片格式";
        }
    });
}
export default ImgFile;
  • 引用
//maxWidth和maxHeight是图片压缩后的最大宽高
ImgFile (e, maxWidth, maxHeight).then((file)=>{
    console.log(file);//返回的是压缩过后的file
})

你可能感兴趣的:(笔记)