在上传到服务器之前,使用 JavaScript 在客户端调整图像大小

问题描述:

我正在寻找一种使用 JavaScript 调整图像客户端大小的方法(真正调整大小,而不仅仅是更改宽度和高度).
我知道可以在 Flash 中执行此操作,但如果可能,我想避免使用它.

I am looking for a way to resize an image client-side with JavaScript (really resize, not just change width and height).
I know it's possible to do it in Flash but I would like to avoid it if possible.

网络上有什么开源算法吗?

Is there any open source algorithm somewhere on the web?

这是执行此操作的要点:https://gist.github.com/dcollien/312bce1270a5f511bf4a

Here's a gist which does this: https://gist.github.com/dcollien/312bce1270a5f511bf4a

(一个 es6 版本,一个 .js 版本,可以包含在脚本标签中)

(an es6 version, and a .js version which can be included in a script tag)

您可以按如下方式使用它:

You can use it as follows:

<input type="file" id="select">
<img id="preview">
<script>
document.getElementById('select').onchange = function(evt) {
    ImageTools.resize(this.files[0], {
        width: 320, // maximum width
        height: 240 // maximum height
    }, function(blob, didItResize) {
        // didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
        document.getElementById('preview').src = window.URL.createObjectURL(blob);
        // you can also now upload this blob using an XHR.
    });
};
</script>

它包括一堆支持检测和 polyfill,以确保它可以在我能管理的尽可能多的浏览器上运行.

It includes a bunch of support detection and polyfills to make sure it works on as many browsers as I could manage.

(它也会忽略 gif 图像 - 如果它们是动画的)

(it also ignores gif images - in case they're animated)