Javascript:调整base64图像并以非同步方式返回字符串

时间:2014-12-21 09:21:49

标签: javascript

我搜索了足够多的示例,并找到了如何调整图像大小的解决方案:

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();
}

function resizeImage() {
    var newDataUri = imageToDataUri(this, 10, 10); // resize to 10x10
    return newDataUri;
}

这是我的问题:

我有每个项目基于64个图像字符串的对象列表:group.mAvatarImgBase64Str。该字符串大于10x10,我需要用新的String替换它。

到目前为止,我做到了:

  if (group.mAvatarImgBase64Str !== 'none') {

            var img = new Image();
            img.onload = resizeImage;
            img.src = group.mAvatarImgBase64Str;
            // group.mAvatarImgBase64Str = ?? 
  }

如果我在resizeImage方法中打印出新值 - 它已正确调整大小,但是:

如何将新字符串添加回group.mAvatarImgBase64Str

onload任务是异步的,我需要类似的东西:

 group.mAvatarImgBase64Str = resize(group.mAvatarImgBase64Str, 10, 10);

谢谢,

1 个答案:

答案 0 :(得分:2)

你应该能够这样做:

if (group.mAvatarImgBase64Str !== 'none') {

    (function(group) {
        var img = new Image();
        img.onload = function() {
            group.mAvatarImgBase64Str = resizeImage.call(this);
        }
        img.src = group.mAvatarImgBase64Str;
    })(group);

}

如果您使用for循环迭代对象数组,则需要额外的IIFE。如果您使用forEach循环,则不需要它。