如何在浏览器中通过Javascript压缩图像?

pom*_*meh 71 javascript compression image cross-browser

TL; DR;

有没有办法在上传之前直接在浏览器端压缩图像(主要是jpeg,png和gif)?我很确定JavaScript可以做到这一点,但我找不到实现它的方法.


这是我想要实现的完整场景:

  • 用户访问我的网站,并通过input type="file"元素选择图像,
  • 这个图像是通过JavaScript检索的,我们做了一些验证,如正确的文件格式,最大文件大小等,
  • 如果一切正常,页面上会显示图像的预览,
  • 用户可以进行一些基本操作,例如将图像旋转90°/ -90°,按照预定义的比例裁剪等,或者用户可以上传另一张图像并返回步骤1,
  • 当用户满意时,编辑后的图像会被压缩并在本地"保存"(不保存到文件中,但在浏览器内存/页面中), -
  • 用户填写表格,其中包含姓名,年龄等数据,
  • 用户单击"完成"按钮,然后将包含数据+压缩图像的表单发送到服务器(不带AJAX),

直到最后一步的完整过程应该在客户端完成,并且应该与最新的Chrome和Firefox,Safari 5+和IE 8+兼容.如果可能,只应使用JavaScript(但我很确定这是不可能的).

我现在没有编码任何东西,但我已经考虑过了.可以通过File API在本地读取文件,可以使用Canvas元素完成图像预览和编辑,但是我找不到一种方法来执行图像压缩部分.

根据html5please.comcaniuse.com,支持这些浏览器非常困难(感谢IE),但可以使用FlashFanvasFileReader之类的polyfill来完成.

实际上,目标是减小文件大小,因此我将图像压缩视为一种解决方案.但是,我知道上传的图像将在我的网站上显示,每次都在同一个地方,我知道这个显示区域的尺寸(例如200x400).因此,我可以调整图像大小以适应这些尺寸,从而减小文件大小.我不知道这种技术的压缩率是多少.

你怎么看 ?你有什么建议告诉我吗?你知道在JavaScript中压缩浏览器图像的方法吗?谢谢你的回复.

psy*_*ood 125

简而言之:

  • 使用带有.readAsArrayBuffer的HTML5 FileReader API读取文件
  • 使用文件数据创建e Blob并使用window.URL.createObjectURL(blob)获取其URL
  • 创建新的Image元素并将其src设置为文件blob url
  • 将图像发送到画布.画布大小设置为所需的输出大小
  • 通过canvas.toDataURL("image/jpeg",0.7)从画布返回缩小的数据(设置自己的输出格式和质量)
  • 将新的隐藏输入附加到原始表单,并将dataURI图像基本上作为普通文本传输
  • 在后端,读取dataURI,从Base64解码,然后保存

来源:代码.

  • 缩小是指在高度和宽度方面制作更小尺寸的图像.这真的是压缩.这是有损压缩,但肯定是压缩.它不会降低像素的尺寸,它只是将一些像素推到相同的颜色,这样压缩就可以用更少的比特来击中这些颜色.无论如何,JPEG都为像素内置压缩,但是在有损模式下,它表示可以将一些颜色称为相同的颜色.那仍然是压缩.关于图形的缩小通常是指实际尺寸的变化. (5认同)
  • @Nicholas Kyriakides,这不是很好的区分.大多数编解码器都不是无损的,所以它们适合你的"缩减"定义(即你不能恢复到100). (4认同)
  • 我只想说:文件可以直接进入`URL.createObjectUrl()`,而无需将文件变成blob;该文件算作一个blob。 (4认同)
  • @NicholasKyriakides我可以确认`canvas.toDataURL(“ image / jpeg”,0.7)`有效地压缩了它,它以质量70(相对于默认质量100)保存了JPEG。 (2认同)
  • 如果有人需要的话,我已经为 Psychowood 的代码示例添加了一个演示器 jsfiddle:https://jsfiddle.net/Abeeee/0wxeugrt/9/ (2认同)

Dan*_*don 13

@PsychoWoods的回答很好.我想提供自己的解决方案.此Javascript函数获取图像数据URL和宽度,将其缩放到新宽度,并返回新的数据URL.

// Take an image URL, downscale it to the given width, and return a new image URL.
function downscaleImage(dataUrl, newWidth, imageType, imageArguments) {
    "use strict";
    var image, oldWidth, oldHeight, newHeight, canvas, ctx, newDataUrl;

    // Provide default values
    imageType = imageType || "image/jpeg";
    imageArguments = imageArguments || 0.7;

    // Create a temporary image so that we can compute the height of the downscaled image.
    image = new Image();
    image.src = dataUrl;
    oldWidth = image.width;
    oldHeight = image.height;
    newHeight = Math.floor(oldHeight / oldWidth * newWidth)

    // Create a temporary canvas to draw the downscaled image on.
    canvas = document.createElement("canvas");
    canvas.width = newWidth;
    canvas.height = newHeight;

    // Draw the downscaled image on the canvas and return the new data URL.
    ctx = canvas.getContext("2d");
    ctx.drawImage(image, 0, 0, newWidth, newHeight);
    newDataUrl = canvas.toDataURL(imageType, imageArguments);
    return newDataUrl;
}
Run Code Online (Sandbox Code Playgroud)

此代码可以在您拥有数据URL的任何地方使用,并且需要缩小图像的数据URL.

  • 提醒一下,有时 image.width/height 会返回 0,因为它尚未加载。您可能需要将其转换为异步函数并收听 image.onload 以获得正确的图像和高度。 (2认同)

Sim*_*olm 13

我看到其他答案中缺少两件事:

  • canvas.toBlob(如果可用)更canvas.toDataURL高效,也是异步.
  • 文件 - >图像 - >画布 - >文件转换丢失EXIF数据; 特别是,关于图像旋转的数据通常由现代手机/平板电脑设定.

以下脚本处理这两点:

// From https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob, needed for Safari:
if (!HTMLCanvasElement.prototype.toBlob) {
    Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
        value: function(callback, type, quality) {

            var binStr = atob(this.toDataURL(type, quality).split(',')[1]),
                len = binStr.length,
                arr = new Uint8Array(len);

            for (var i = 0; i < len; i++) {
                arr[i] = binStr.charCodeAt(i);
            }

            callback(new Blob([arr], {type: type || 'image/png'}));
        }
    });
}

window.URL = window.URL || window.webkitURL;

// Modified from https://stackoverflow.com/a/32490603, cc by-sa 3.0
// -2 = not jpeg, -1 = no data, 1..8 = orientations
function getExifOrientation(file, callback) {
    // Suggestion from http://code.flickr.net/2012/06/01/parsing-exif-client-side-using-javascript-2/:
    if (file.slice) {
        file = file.slice(0, 131072);
    } else if (file.webkitSlice) {
        file = file.webkitSlice(0, 131072);
    }

    var reader = new FileReader();
    reader.onload = function(e) {
        var view = new DataView(e.target.result);
        if (view.getUint16(0, false) != 0xFFD8) {
            callback(-2);
            return;
        }
        var length = view.byteLength, offset = 2;
        while (offset < length) {
            var marker = view.getUint16(offset, false);
            offset += 2;
            if (marker == 0xFFE1) {
                if (view.getUint32(offset += 2, false) != 0x45786966) {
                    callback(-1);
                    return;
                }
                var little = view.getUint16(offset += 6, false) == 0x4949;
                offset += view.getUint32(offset + 4, little);
                var tags = view.getUint16(offset, little);
                offset += 2;
                for (var i = 0; i < tags; i++)
                    if (view.getUint16(offset + (i * 12), little) == 0x0112) {
                        callback(view.getUint16(offset + (i * 12) + 8, little));
                        return;
                    }
            }
            else if ((marker & 0xFF00) != 0xFF00) break;
            else offset += view.getUint16(offset, false);
        }
        callback(-1);
    };
    reader.readAsArrayBuffer(file);
}

// Derived from https://stackoverflow.com/a/40867559, cc by-sa
function imgToCanvasWithOrientation(img, rawWidth, rawHeight, orientation) {
    var canvas = document.createElement('canvas');
    if (orientation > 4) {
        canvas.width = rawHeight;
        canvas.height = rawWidth;
    } else {
        canvas.width = rawWidth;
        canvas.height = rawHeight;
    }

    if (orientation > 1) {
        console.log("EXIF orientation = " + orientation + ", rotating picture");
    }

    var ctx = canvas.getContext('2d');
    switch (orientation) {
        case 2: ctx.transform(-1, 0, 0, 1, rawWidth, 0); break;
        case 3: ctx.transform(-1, 0, 0, -1, rawWidth, rawHeight); break;
        case 4: ctx.transform(1, 0, 0, -1, 0, rawHeight); break;
        case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
        case 6: ctx.transform(0, 1, -1, 0, rawHeight, 0); break;
        case 7: ctx.transform(0, -1, -1, 0, rawHeight, rawWidth); break;
        case 8: ctx.transform(0, -1, 1, 0, 0, rawWidth); break;
    }
    ctx.drawImage(img, 0, 0, rawWidth, rawHeight);
    return canvas;
}

function reduceFileSize(file, acceptFileSize, maxWidth, maxHeight, quality, callback) {
    if (file.size <= acceptFileSize) {
        callback(file);
        return;
    }
    var img = new Image();
    img.onerror = function() {
        URL.revokeObjectURL(this.src);
        callback(file);
    };
    img.onload = function() {
        URL.revokeObjectURL(this.src);
        getExifOrientation(file, function(orientation) {
            var w = img.width, h = img.height;
            var scale = (orientation > 4 ?
                Math.min(maxHeight / w, maxWidth / h, 1) :
                Math.min(maxWidth / w, maxHeight / h, 1));
            h = Math.round(h * scale);
            w = Math.round(w * scale);

            var canvas = imgToCanvasWithOrientation(img, w, h, orientation);
            canvas.toBlob(function(blob) {
                console.log("Resized image to " + w + "x" + h + ", " + (blob.size >> 10) + "kB");
                callback(blob);
            }, 'image/jpeg', quality);
        });
    };
    img.src = URL.createObjectURL(file);
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

inputfile.onchange = function() {
    // If file size > 500kB, resize such that width <= 1000, quality = 0.9
    reduceFileSize(this.files[0], 500*1024, 1000, Infinity, 0.9, blob => {
        let body = new FormData();
        body.set('file', blob, blob.name || "file.jpg");
        fetch('/upload-image', {method: 'POST', body}).then(...);
    });
};
Run Code Online (Sandbox Code Playgroud)


小智 11

你可以看看image-conversion,在这里试试 -->演示页面

在此处输入图片说明

  • 请添加有关链接资源的一些信息 (2认同)
  • 它是迄今为止最好的插件,超级易于使用且功能强大。这可能是最好的答案。感谢分享 (2认同)

Eyn*_*ave 11

尝试这个可定制的纯 JS 示例 - 压缩超过 90%:

   <div id="root">
        <p>Upload an image and see the result</p>
        <input id="img-input" type="file" accept="image/*" style="display:block" />
    </div>

    <script>
        const MAX_WIDTH = 320;
        const MAX_HEIGHT = 180;
        const MIME_TYPE = "image/jpeg";
        const QUALITY = 0.7;

        const input = document.getElementById("img-input");
        input.onchange = function (ev) {
            const file = ev.target.files[0]; // get the file
            const blobURL = URL.createObjectURL(file);
            const img = new Image();
            img.src = blobURL;
            img.onerror = function () {
                URL.revokeObjectURL(this.src);
                // Handle the failure properly
                console.log("Cannot load image");
            };
            img.onload = function () {
                URL.revokeObjectURL(this.src);
                const [newWidth, newHeight] = calculateSize(img, MAX_WIDTH, MAX_HEIGHT);
                const canvas = document.createElement("canvas");
                canvas.width = newWidth;
                canvas.height = newHeight;
                const ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, newWidth, newHeight);
                canvas.toBlob(
                    (blob) => {
                        // Handle the compressed image. es. upload or save in local state
                        displayInfo('Original file', file);
                        displayInfo('Compressed file', blob);
                    },
                    MIME_TYPE,
                    QUALITY
                );
                document.getElementById("root").append(canvas);
            };
        };

        function calculateSize(img, maxWidth, maxHeight) {
            let width = img.width;
            let height = img.height;

            // calculate the width and height, constraining the proportions
            if (width > height) {
                if (width > maxWidth) {
                    height = Math.round((height * maxWidth) / width);
                    width = maxWidth;
                }
            } else {
                if (height > maxHeight) {
                    width = Math.round((width * maxHeight) / height);
                    height = maxHeight;
                }
            }
            return [width, height];
        }

        // Utility functions for demo purpose

        function displayInfo(label, file) {
            const p = document.createElement('p');
            p.innerText = `${label} - ${readableBytes(file.size)}`;
            document.getElementById('root').append(p);
        }

        function readableBytes(bytes) {
            const i = Math.floor(Math.log(bytes) / Math.log(1024)),
                sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

            return (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i];
        }
    </script>
Run Code Online (Sandbox Code Playgroud)

  • 到目前为止最好的答案。代码也干净 (2认同)

Ric*_*ick 8

我发现与接受的答案相比,有更简单的解决方案。

  • 使用 HTML5 FileReader API 读取文件.readAsArrayBuffer
  • 使用文件数据创建一个 Blob 并获取其 urlwindow.URL.createObjectURL(blob)
  • 创建新的 Image 元素并将其 src 设置为文件 blob url
  • 将图像发送到画布。画布大小设置为所需的输出大小
  • 通过(设置您自己的输出格式和质量)从画布获取缩小的数据canvas.toDataURL("image/jpeg",0.7)
  • 将新的隐藏输入附加到原始表单,并将 dataURI 图像基本上作为普通文本传输
  • 在后端,读取dataURI,从Base64解码,然后保存

根据你的问题:

有没有办法在上传之前直接在浏览器端压缩图像(主要是 jpeg、png 和 gif)

我的解决方案:

  1. 直接使用该文件创建一个 blob URL.createObjectURL(inputFileElement.files[0])

  2. 与接受的答案相同。

  3. 与接受的答案相同。值得一提的是,画布大小是必须的,使用img.widthimg.height来设置canvas.widthcanvas.height。不是img.clientWidth

  4. 获取按比例缩小的图像canvas.toBlob(callbackfunction(blob){}, 'image/jpeg', 0.5)。设置'image/jpg'没有效果。image/png也支持。在体内创建一个新File对象。callbackfunction let compressedImageBlob = new File([blob])

  5. 添加新的隐藏输入或通过 javascript 发送。服务器不必解码任何内容。

检查https://javascript.info/binary了解所有信息。读完这一章后我找到了解决方案。


代码:

    <!DOCTYPE html>
    <html>
    <body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
      Select image to upload:
      <input type="file" name="fileToUpload" id="fileToUpload" multiple>
      <input type="submit" value="Upload Image" name="submit">
    </form>
    </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

这段代码看起来远没有其他答案那么可怕。

更新:

必须把所有东西都放进去img.onload。否则canvas将无法按照canvas指定的时间正确获取图像的宽度和高度。

    function upload(){
        var f = fileToUpload.files[0];
        var fileName = f.name.split('.')[0];
        var img = new Image();
        img.src = URL.createObjectURL(f);
        img.onload = function(){
            var canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0);
            canvas.toBlob(function(blob){
                    console.info(blob.size);
                    var f2 = new File([blob], fileName + ".jpeg");
                    var xhr = new XMLHttpRequest();
                    var form = new FormData();
                    form.append("fileToUpload", f2);
                    xhr.open("POST", "upload.php");
                    xhr.send(form);
            }, 'image/jpeg', 0.5);
        }
    }
Run Code Online (Sandbox Code Playgroud)

3.4MB .pngimage/jpeg使用参数集进行文件压缩测试。

    |0.9| 777KB |
    |0.8| 383KB |
    |0.7| 301KB |
    |0.6| 251KB |
    |0.5| 219kB |
Run Code Online (Sandbox Code Playgroud)


uin*_*tea 6

对于现代浏览器使用createImageBitmap()而不是img.onload

async function compressImage(blobImg, percent) {
  let bitmap = await createImageBitmap(blobImg);
  let canvas = document.createElement("canvas");
  let ctx = canvas.getContext("2d");
  canvas.width = bitmap.width;
  canvas.height = bitmap.height;
  ctx.drawImage(bitmap, 0, 0);
  let dataUrl = canvas.toDataURL("image/jpeg", percent/100);
  return dataUrl;
}

inputImg.addEventListener('change', async(e) => {
  let img = e.target.files[0];
  console.log('File Name: ', img.name)
  console.log('Original Size: ', img.size.toLocaleString())
  
  let imgCompressed = await compressImage(img, 75) // set to 75%
  let compSize = atob(imgCompressed.split(",")[1]).length;
  console.log('Compressed Size: ', compSize.toLocaleString())
  //console.log(imgCompressed)
})
Run Code Online (Sandbox Code Playgroud)
<input type="file" id="inputImg">
Run Code Online (Sandbox Code Playgroud)


Rus*_*ggs 5

我对 @daniel-allen-langdon 上面发布的函数有一个问题downscaleImage(),因为image.widthimage.height属性无法立即可用,因为图像加载是异步的

请参阅下面更新的 TypeScript 示例,该示例考虑了这一点,使用async函数,并根据最长尺寸而不仅仅是宽度调整图像大小

function getImage(dataUrl: string): Promise<HTMLImageElement> 
{
    return new Promise((resolve, reject) => {
        const image = new Image();
        image.src = dataUrl;
        image.onload = () => {
            resolve(image);
        };
        image.onerror = (el: any, err: ErrorEvent) => {
            reject(err.error);
        };
    });
}

export async function downscaleImage(
        dataUrl: string,  
        imageType: string,  // e.g. 'image/jpeg'
        resolution: number,  // max width/height in pixels
        quality: number   // e.g. 0.9 = 90% quality
    ): Promise<string> {

    // Create a temporary image so that we can compute the height of the image.
    const image = await getImage(dataUrl);
    const oldWidth = image.naturalWidth;
    const oldHeight = image.naturalHeight;
    console.log('dims', oldWidth, oldHeight);

    const longestDimension = oldWidth > oldHeight ? 'width' : 'height';
    const currentRes = longestDimension == 'width' ? oldWidth : oldHeight;
    console.log('longest dim', longestDimension, currentRes);

    if (currentRes > resolution) {
        console.log('need to resize...');

        // Calculate new dimensions
        const newSize = longestDimension == 'width'
            ? Math.floor(oldHeight / oldWidth * resolution)
            : Math.floor(oldWidth / oldHeight * resolution);
        const newWidth = longestDimension == 'width' ? resolution : newSize;
        const newHeight = longestDimension == 'height' ? resolution : newSize;
        console.log('new width / height', newWidth, newHeight);

        // Create a temporary canvas to draw the downscaled image on.
        const canvas = document.createElement('canvas');
        canvas.width = newWidth;
        canvas.height = newHeight;

        // Draw the downscaled image on the canvas and return the new data URL.
        const ctx = canvas.getContext('2d')!;
        ctx.drawImage(image, 0, 0, newWidth, newHeight);
        const newDataUrl = canvas.toDataURL(imageType, quality);
        return newDataUrl;
    }
    else {
        return dataUrl;
    }

}
Run Code Online (Sandbox Code Playgroud)