Is it possible to get the height / width of an image that is not in the DOM?

Is it possible to get the height and width of an image in a file system using JavaScript (i.e. an image that is not part of the DOM)? Or will I have to use JavaScript to insert the image into the DOM and capture the dimensions in this way?

I ask because I am writing a JavaScript method to render the user interface component on the fly created by RaphaΓ«l, which accepts three image paths as part of the method parameters. They are then used to render the aforementioned user interface component, and I need image sizes for positioning purposes.

Thanks in advance.

+6
source share
4 answers

I think that while the image is loaded, you can capture the width and height - you do not have to enter it in the DOM. For instance:

var tmp = new Image(); tmp.onload = function() { console.log(tmp.width + ' x ' + tmp.height); } tmp.src = 'http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4'; 
+9
source

You cannot get into the "file system", but you can do this:

 v = new Image(); v.onload = function() { alert("size: " + String(v.width) + 'x' + String(v.height)); }; v.src = "http://www.gravatar.com/avatar/96269f5a69115aa0e461b6334292d651?s=32&d=identicon&r=PG"; 

Do you consider this an β€œadd to the DOM”?

+4
source

You can upload an image with the code:

 var img=new Image(),imgWidth,imgHeight; img.onerror=img.onload=function(ev) { ev=ev||event; if(ev.type==="error") { imgWidth=imgHeight=-1; // error loading image resourse } else { imgWidth=this.width; // orimgWidth=img.width imgHeight=this.height; // imgHeight=img.height } } img.src="url_to_image_file"; 
+1
source

Is it possible to get the height and width of an image in a file system using JavaScript (i.e. an image that is not part of the DOM)?

  • Not

Or will I need to use JavaScript to insert the image into the DOM and capture the dimensions this way?

  • Yes
-5
source

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


All Articles