我需要为用户提供一种将照片以 jpeg 格式上传到其网站的方法。但是,照片的原始尺寸非常大,我想让用户在上传前调整大小选项变得非常轻松。似乎我唯一的选择是在通过 Web 服务上传照片之前调整照片大小的客户端应用程序,或者调整图像大小的上传操作的客户端 JavaScript Hook 。第二个选项是非常试探性的,因为我没有 JavaScript 图像大小调整库,并且很难让 JavaScript 运行我当前的调整大小工具 ImageMagick。
我相信这种情况并不少见,我们将不胜感激一些建议或指向执行此操作的网站的指示。
最佳答案
2011 年,我们知道可以使用 File API 和 canvas 来实现。 这目前仅适用于 firefox 和 chrome。 这是一个例子:
var file = YOUR_FILE,
fileType = file.type,
reader = new FileReader();
reader.onloadend = function() {
var image = new Image();
image.src = reader.result;
image.onload = function() {
var maxWidth = 960,
maxHeight = 960,
imageWidth = image.width,
imageHeight = image.height;
if (imageWidth > imageHeight) {
if (imageWidth > maxWidth) {
imageHeight *= maxWidth / imageWidth;
imageWidth = maxWidth;
}
}
else {
if (imageHeight > maxHeight) {
imageWidth *= maxHeight / imageHeight;
imageHeight = maxHeight;
}
}
var canvas = document.createElement('canvas');
canvas.width = imageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
// The resized file ready for upload
var finalFile = canvas.toDataURL(fileType);
}
}
reader.readAsDataURL(file);
关于javascript - 上传前调整图片大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/961913/