Skip to content

Latest commit

 

History

History
138 lines (125 loc) · 4.88 KB

前端图片压缩方案.md

File metadata and controls

138 lines (125 loc) · 4.88 KB

前端图片压缩方案

压缩图片原理:

先通过 js 中 img 构造函数,实例化 img 对象,后将图片的路径给转移到中,再建立一个 canvas 画布,后对画布进行各方面的数值的设置。

如代码所示:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            canvas {
                border: 1px solid black;
            }
        </style>
    </head>
    <body>
        <canvas id="mycanvas" width="1000" height="1000"></canvas>
        //设置画布的宽高
    </body>
</html>

js 部分

//图片压缩,利用image对象 和canvas绘图将图像压缩
window.onload = function () {
    var mycanvas = document.getElementById("mycanvas");
    var ctx = mycanvas.getContext("2d");
    var img = new Image();
    img.src = "./实验.jpg";
    img.onload = function () {
        // alert('加载完毕')
        // 将图片画到canvas上面上去
        ctx.drawImage(img, 0, 0, 500, 500);
    };
};

base64 压缩

//压缩base64方法
function dealImage(base64, w, callback) {
    var newImage = new Image();
    var quality = 0.6; //压缩系数0-1之间
    newImage.src = base64;
    newImage.setAttribute("crossOrigin", "Anonymous"); //url为外域时需要
    var imgWidth, imgHeight;
    newImage.onload = function () {
        imgWidth = this.width;
        imgHeight = this.height;
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        if (Math.max(imgWidth, imgHeight) > w) {
            if (imgWidth > imgHeight) {
                canvas.width = w;
                canvas.height = (w * imgHeight) / imgWidth;
            } else {
                canvas.height = w;
                canvas.width = (w * imgWidth) / imgHeight;
            }
        } else {
            canvas.width = imgWidth;
            canvas.height = imgHeight;
            quality = 0.6;
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
        var base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句
        callback(base64); //必须通过回调函数返回,否则无法及时拿到该值
    };
}
/**
 * 返回压缩后的base64
 * @param file
 */
export function getPicCompress(file: File) {
    return (
        new Promise() <
        string >
        ((resolve, reject) => {
            let quality = 0.8; // 压缩系数0-1之间
            let reader = new FileReader();
            reader.readAsDataURL(file);
            let imgWidth;
            let imgHeight;
            reader.onload = function (e) {
                let image: any = new Image(); // 新建一个img标签(还没嵌入DOM节点)
                image.src = e.target.result;
                image.onload = function () {
                    imgWidth = image.width;
                    imgHeight = image.height;
                    let canvas = document.createElement("canvas");
                    let ctx = canvas.getContext("2d");
                    if (Math.max(imgWidth, imgHeight) > 1024) {
                        if (imgWidth > imgHeight) {
                            canvas.width = 1024;
                            canvas.height = (1024 * imgHeight) / imgWidth;
                        } else {
                            canvas.height = 1024;
                            canvas.width = (1024 * imgWidth) / imgHeight;
                        }
                    } else {
                        canvas.width = imgWidth;
                        canvas.height = imgHeight;
                        quality = 0.8;
                    }
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
                    let base64 = canvas.toDataURL("image/jpeg", quality); // 压缩语句
                    resolve(base64); // 必须通过回调函数返回,否则无法及时拿到该值
                };
                reader.onerror = (error) => reject(error);
            };
        })
    );
}

基本都是通过图片转 canvas 然后通过 toDataURL 到处低质量的图完成的压缩。

toDataURl 方法接收两个参数,返回一个包含图片展示的 data URI 。可以使用 type 参数其类型,默认为 PNG 格式。图片的分辨率为 96dpi。

  1. type 可选 图片格式,默认为 image/png
  2. encoderOptions 可选 在指定图片格式为 image/jpeg 或 image/webp 的情况下,可以从 0 到 1 的区间内选择图片的质量。如果超出取值范围,将会使用默认值 0.92。其他参数会被忽略。