我使用画布将图片转换为base64编码的字符串:
if (inputImage.get(0).files.length) {
var image = $("#datatransfer_food_image")[0];
var image_width = image.naturalWidth;
var image_width_target = image_width;
var image_height = image.naturalHeight;
var image_height_target = image_height;
if ((image_width > 1080) || (image_height > 1080)) {
var aspectRatio = 0.0;
if (image_width > image_height) {
aspectRatio = (image_width / image_height);
image_width_target = 1080;
image_height_target = (1080 / aspectRatio);
} else {
aspectRatio = (image_height / image_width);
image_width_target = (1080 / aspectRatio);
image_height_target = 1080;
}
}
var canvas = document.createElement("canvas");
canvas.width = image_width_target;
canvas.height = image_height_target;
var context = canvas.getContext("2d");
context.fillStyle = "#fff";
context.drawImage(image, 0, 0, image_width_target, image_height_target);
inputImageName = inputImage.val();
inputImageName = inputImageName.substring((inputImageName.lastIndexOf("\\") + 1), inputImageName.length);
inputImageSource = canvas.toDataURL("image/jpeg");
console.log("input iamge widht: " + image_width);
console.log("input image widht: " + image_width_target);
console.log("input image height: " + image_height_target);
console.log("input image source: " + inputImageSource);
} else {
error = true;
$("#food_picture_missing").show();
}
此代码通常正常工作。例如这张照片:
但如果我以此图片为例(也是jpg):
inputImageSource
的值仅为:
data:,
怎么会这样?我在这里做错了一些图片的编码是相关的,有些只是产生了像data:,
这样的字符串?
编辑
我使用以下jquery代码选择图像:
$(document).on("change", "#datatransfer_food_image_input", function() {
if (typeof (FileReader) != "undefined") {
var image_scanner = $("#datatransfer_food_image_div");
var reader = new FileReader();
reader.onload = function(e) {
$("#datatransfer_food_image").attr("src", e.target.result);
$("#datatransfer_food_image").removeClass("icon-scanner");
$("#datatransfer_food_image").addClass("image-upload-image");
}
reader.readAsDataURL($(this)[0].files[0]);
} else {
}
});
EIDT 2
input image widht: Infinity
datatransfer.js:451 input image height: 1080
datatransfer.js:452 input image source: data:,
图像宽度无穷大似乎是个问题。 我添加了更多代码。
编辑3
它表明画布不是问题。宽度和高度以及纵横比的计算是。如果您拍摄第一张照片(即风景照片):
width greater than height
aspect ratio: 1.3333333333333333, height: 2448, width: 3264
input image widht: 1080
input image height: 810
如果你拍第二张照片(肖像):
width smaller than height
ratio: 0, height: 3264, width: 2448
input image widht: Infinity
input image height: 1080
但它是相同的计算过程,为什么0而不是1.33?