只是想分享我如何解决我的问题。
因为我想要一个纯粹的 javascript 解决方案,所以我使用一次性画布元素来完成肮脏的工作。
这是我的代码:
function resizeImage(url, width, height, callback, file) {
console.log("In_resizeImage");
var sourceImage = new Image();
sourceImage.onload = (function (f) {
return function (evt) {
console.log("In_sourceImage_onload");
console.log("sourceImage.width:" + sourceImage.width);
console.log("sourceImage.height:" + sourceImage.height);
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
if (sourceImage.width == sourceImage.height) {
canvas.getContext("2d").drawImage(sourceImage, 0, 0, width, height);
} else {
minVal = Math.min(sourceImage.width, sourceImage.height);
if (sourceImage.width > sourceImage.height) {
canvas.getContext("2d").drawImage(sourceImage, (sourceImage.width - minVal) / 2, 0, minVal, minVal, 0, 0, width, height);
} else {
canvas.getContext("2d").drawImage(sourceImage, 0, (sourceImage.height - minVal) / 2, minVal, minVal, 0, 0, width, height);
}
}
callback(canvas.toDataURL(), f);
}
})(file);
sourceImage.src = url;
}
我直接处理图像文件,因此我能够使用 Image 对象。对于其他人来说,可能需要进行一些调整。