Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data:image/jpeg;base64 how to get its width and height in pixels

How do you get the width and height in pixels image which its src is in data:image/jpeg;base64 ?

Didn't succeed using setting img.src to it and then calling width().

var img = jQuery("<img src="+oFREvent.target.result+">");
img.width() // = 0
like image 353
Alon Avatar asked Jul 14 '13 16:07

Alon


2 Answers

This will work :

var img = new Image();
img.onload = function() {
    alert(this.width);
}
img.src = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAA.......";

FIDDLE

I made sure the base64 was valid by converting an image here, and the onload function should come before setting the source of the image.

like image 50
adeneo Avatar answered Sep 22 '22 10:09

adeneo


You have to wait for the image to be loaded (or complete, if cached). This will result in an asynchronous callback operation:

// pure JS:

var img = new Image();
img.src = myDataString;
if (img.complete) { // was cached
    alert('img-width: '+img.width);
}
else { // wait for decoding
    img.onload = function() {
       alert('img-width: '+img.width);
    }
}

Note: I once had the same problem with a project using jQuery. jQuery doesn't provide an access to the image directly enough just after you have created it. It seems, it's not possible to be done, but in pure JS. But you could try a timeout-loop and wait for the img-width to have a value (and catch any loading/decoding errors).

[Edit, see also comments] Why this works (why there is no race-condition):

JS is single-threaded, meaning there's only one part of code executed at a given time. Any events will be queued until the current scope is exited and will only fire then. Thanks to late-binding, any listeners will be evaluated only then (after the current scope has been executed). So the handler will be present and listening as soon as the onload-Event is fired, regardless, if the listener was setup before or after setting the src-attribute. In contrast to this, the complete-flag is set as soon as the src-attribute is set.

like image 21
masswerk Avatar answered Sep 22 '22 10:09

masswerk