admin管理员组

文章数量:1296847

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

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
Share Improve this question edited Jul 14, 2013 at 16:09 NullUserException 85.5k30 gold badges211 silver badges237 bronze badges asked Jul 14, 2013 at 16:02 AlonAlon 3,90610 gold badges46 silver badges65 bronze badges 2
  • Did you wait for the image to load? – Musa Commented Jul 14, 2013 at 16:04
  • @Musa, Don't think so, look at my edit – Alon Commented Jul 14, 2013 at 16:05
Add a ment  | 

2 Answers 2

Reset to default 5

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 e before setting the source of the image.

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

// pure JS:

var img = new Image();
img.src = myDataString;
if (img.plete) { // 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 ments] 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 plete-flag is set as soon as the src-attribute is set.

本文标签: javascriptdataimagejpegbase64 how to get its width and height in pixelsStack Overflow