0

I am able to resize an image using an image element but can't seem to get the new URL. I found a function that would work but the event fires too late.

I have an onload event on the image element and after that function I set the img.src to the URL I want to apply but the onload event fires after it leaves the function and then comes back. But that is too late. I am using Chrome for this.

   function getBase64FromImageUrl(url) {
     var img = new Image();

     img.setAttribute('crossOrigin', 'anonymous');

     img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = this.width;
        canvas.height = this.height;

        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);

        var dataURL = canvas.toDataURL("image/png");

        alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
     };

     img.src = url;
   }

It is called like this:

           var imgURL = URL.createObjectURL(file);

           // Set img src to ObjectURL
           showPicture.src = imgURL;
           resizeImageToImg(showPicture, "200", "120");

           newURL = getBase64FromImageUrl(showPicture.src);

           showPicture.src = newURL;

It gets to the showPicture.src = newURL before the onload event fires, so newURL is undefined.

Pretty much all the functions I have seen use this technique, using the onload event so that after everything is loaded, you can get to the width and the height.

Am I doing something wrong here?

Thanks,

Tom

Brigand
  • 84,529
  • 20
  • 165
  • 173
tshad
  • 335
  • 2
  • 4
  • 18
  • `newURL` is undefined because your `getBase64FromImageUrl()` function doesn't have a `return` statement. (But still to fix that you have to deal with the asynchronous execution of the `onload` handler. You could return a promise, or update your function to accept a callback instead of returning a value.) – nnnnnn Mar 28 '17 at 01:51
  • Ps : you don't need to set your `showPicture`'s src to `url`. Set it only to `newURL`, and only in a callback of `getBase64FromImageUrl` – Kaiido Mar 28 '17 at 02:35

1 Answers1

0

Try that instead:

var imgURL = URL.createObjectURL(file);
// Set img src to ObjectURL
showPicture.onload = function () {
  resizeImageToImg(showPicture, "200", "120");
  newURL = getBase64FromImageUrl(showPicture.src);
  showPicture.onload = null;
  showPicture.src = newURL;
}
showPicture.src = imgURL;
mika
  • 1,411
  • 1
  • 12
  • 23