图像在上传到服务器之前使用JavaScript调整客户端的大小 [英] Image resizing client-side with JavaScript before upload to the server
问题描述
我想知道在技术上是否可以使用JavaScript在客户端调整图像大小(确实调整大小,而不仅仅是更改宽度和高度)。我知道可以在Flash中完成它但我想尽可能避免它。网上某处是否有开源算法?
I would like to know if it is technically possible to resize an image at a 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?
推荐答案
这里有一个要点:$ b $ b 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)
这篇关于图像在上传到服务器之前使用JavaScript调整客户端的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!