无法从 javascript canvas 获取 base64 调整大小的图像

Can't get base64 resized image from javascript canvas

我有两个主要问题。我正在尝试根据

中的答案调整 base64 图像的大小

JavaScript reduce the size and quality of image with based64 encoded code

这看起来很简单,只是我只需要从该函数中获取 base64 字符串,而不需要 data:image...header。

我试过这样修改函数:

function resizeBase64Img(base64, width, height) {
    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    var context = canvas.getContext("2d");
    var deferred = $.Deferred();
    $("<img/>").attr("src", "data:image/gif;base64," + base64).load(function () {
        context.scale(width / this.width, height / this.height);
        context.drawImage(this, 0, 0);
        deferred.resolve($("<img/>").attr("src", canvas.toDataURL()));
    });
    var result = canvas.toDataURL();
    return result.substr(result.indexOf(",") + 1)
}

其中 returns 一个 base64 字符串。此字符串已损坏,并且永远不会正确显示。为什么会发生这种情况,我该如何解决?

另一个问题是,有没有办法根据百分比而不是像素大小来调整图像大小?

谢谢

我最终根据我发现的另一个 canvas 函数重写了该函数。此函数获取 base64 img 的 src,修改大小并将 base64 中的结果分配给另一个元素:

function resizeBase64Img(url, width, height) {
    var img = new Image();
    img.setAttribute('crossOrigin', 'anonymous');
    img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.scale(width/this.width,  height/this.height);
        ctx.drawImage(this, 0, 0);
        result=canvas.toDataURL();
        $('#ASSIGNEDELEMENT').val(result.substr(result.indexOf(",") + 1));      
    };

    img.src = url;
}

并且应该这样调用:

            resizeBase64Img($('#image').attr('src'),300,300);