js实现图片压缩、分辨率等比例缩放

<input type="file" id="file" />
<script>
    function imageScale(width, originWidth, originHeight) {
        const scaleRatio = width / originWidth;
        const scaleHeight = scaleRatio * originHeight;
        return [width, scaleHeight];
    }

    function compress(file, scaleWidth, quality = 0.5) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = (e) => {
                let img = new Image();
                img.src = e.target.result;
                img.onload = function () {
                    // 等比例缩放图片
                    const [width, height] = imageScale(
                        scaleWidth,
                        img.width,
                        img.height
                    );
                    let canvas = document.createElement("canvas");
                    img.width = canvas.width = width;
                    img.height = canvas.height = height;
                    let ctx = canvas.getContext("2d");
                    ctx.drawImage(img, 0, 0, img.width, img.height);
                    canvas.toBlob(
                        (blob) => {
                            resolve(blob);
                        },
                        "image/jpeg",
                        quality
                    );
                };

                img.onerror = function () {
                    reject();
                };
            };
        });
    }

    file.onchange = function () {
        compress(this.files[0], 200).then((blob) => {
            let url = window.URL.createObjectURL(blob);
            const img = document.createElement("img");
            img.src = url;
            img.width = 200;
            document.body.appendChild(img);
        });
    };
script>

js实现图片压缩、分辨率等比例缩放_第1张图片

你可能感兴趣的:(javascript,前端,java)