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