我正在将一个base64字符串转换为一张图片,然后将其传递给canvas绘制函数来缩小它。这是基于我在SO上找到的一个脚本。
function imageToDataUri(img, width, height) {
// create an off-screen canvas
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
// set its dimension to target size
canvas.width = width;
canvas.height = height;
// draw source image into the off-screen canvas:
ctx.drawImage(img, 0, 0, width, height);
// encode image to data-uri with base64 version of compressed image
return canvas.toDataURL();
}
我传入图片元素(在此之前已正确检查),有时此脚本能正确工作并将图像更改为正确的大小,而有时它会生成一个空白图像,类似于这样:
iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAAAXNSR0IArs4c6QAAAEJJREFUaAXt0IEAAAAAw6D5Ux/khVBhwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYMGDBgwIABAwYeBwYnQgABzCacsQAAAABJRU5ErkJggg==
我找不到可重复性 - 它发生或者不发生,同一张图片或不同的图片都是如此。
可能出了什么问题?脚本似乎在有一半的时间里工作?其他所有东西都完全相同。
编辑 - 这是上述函数生成图像的方式:
function resizeURI(base64) {
var img = new Image;
// turns base64 into dataURI
var uri = base64ToDataUri(base64);
img.src = uri;
var resizedURI = resizeImage(img);
// turns dataURI into base64 again
resizedURI = resizedURI.substring(resizedURI.indexOf(",") + 1);
return resizedURI;
}
function resizeImage(img) {
var newDataUri = imageToDataUri(img, 50, 50);
return newDataUri;
}