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

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

Failed to configure img.src and then call width ().

var img = jQuery("<img src="+oFREvent.target.result+">"); img.width() // = 0 
+6
source share
2 answers

You need to wait until the image is loaded (or completed if it is saved in the cache). 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 does not provide access to the image immediately enough immediately after its creation. This seems impossible to do, but in pure JS. But you can try timeout and wait for img-width to matter (and catch any errors when loading / decoding).

[Edit, see also comments] Why it works (why there is no racial state):

JS is single-threaded, which means that only one piece of code is currently running. Any events will be queued until the current area is displayed and will only fire. Thanks to late binding, any listeners will be evaluated only then (after completing the current area). Thus, the handler will be present and listened as soon as the onload-Event is triggered, regardless of whether the listener was configured before or after setting the src attribute. In contrast, the full flag is set as soon as the src attribute is set.

+2
source

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 base64 was valid by converting the image here , and the onload function should appear before loading ..

+5
source

Source: https://habr.com/ru/post/949415/


All Articles