我正在寻找一种使用 JavaScript 调整图像客户端大小的方法(真正调整大小,而不仅仅是改变宽度和高度)。
我知道在 Flash 中可以做到这一点,但如果可能的话,我想避免它。
网络上有没有开源算法?
最佳答案
这里有一个要点: https://gist.github.com/dcollien/312bce1270a5f511bf4a
(一个es6版本,一个可以包含在脚本标签中的.js版本)
您可以按如下方式使用它:
<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,以确保它可以在尽可能多的浏览器上运行。
(它也会忽略 gif 图像 - 如果它们是动画的)
关于javascript - 在上传到服务器之前使用 JavaScript 在客户端调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2434458/