我目前正在尝试在上传之前调整图像大小并实现这一点我使用JS / Jquery,必须是客户端。在我的服务器上,我只是拒绝所有大于30MB的请求。
我正在使用此代码:
$( "input[type='file']" ).change(function() {
console.log("function works");
// from an input element
var filesToUpload = this.files;
console.log(filesToUpload);
var img = document.createElement("img");
img.src = window.URL.createObjectURL(this.files[0]);
console.log("image: ", img);
console.log("the image is: ", img.width);
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas = $("#uploading_canvas").get(0);;
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas[0].toDataURL("image/png");
//var file = canvas.mozGetAsFile("foo.png");
});
第一个console.log
输出显示图像在那里,但不知何故它没有宽度或高度。使用此代码上传图像不会改变任何内容。
以下是控制台日志输出:
DataToUrl未定义,因为图像丢失了?
答案 0 :(得分:1)
正如@ymz在评论中解释的那样,图像需要加载时间,因此将图像相关代码包装到另外的onload函数中解决了这个问题。
解决方案如下所示:
$( img ).load(function() {
canvas = $("#uploading_canvas").get(0);
var MAX_WIDTH = 600;
var MAX_HEIGHT = 450;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
});