0

I have two main questions. I'm trying to resize a base64 image according to the answer in

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

This seemed simple enough, except for the fact that I need to get only the base64 string from that function, without the data:image... header.

I tried to modify the function like this:

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

which returns a base64 string. This string is corrupted, and it never displays correctly. Why is this happening and how can I fix it?

The other question is, is there a way to resize the image based on percentage and not on pixel size?

Thanks

user134167
  • 195
  • 3
  • 9

1 Answers1

0

I ended up rewriting the function based on another canvas function I found. This function takes the src of a base64 img, modifies the size and assigns the result in base64 to another element:

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

And it should be invoked like this:

            resizeBase64Img($('#image').attr('src'),300,300);
user134167
  • 195
  • 3
  • 9