JavaScript: Get image dimensions
171,286
Solution 1
var img = new Image();
img.onload = function(){
var height = img.height;
var width = img.width;
// code here to use the dimensions
}
img.src = url;
Solution 2
Make a new Image
var img = new Image();
Set the src
img.src = your_src
Get the width
and the height
//img.width
//img.height
Solution 3
naturalWidth and naturalHeight
var img = document.createElement("img");
img.onload = function (event)
{
console.log("natural:", img.naturalWidth, img.naturalHeight);
console.log("width,height:", img.width, img.height);
console.log("offsetW,offsetH:", img.offsetWidth, img.offsetHeight);
}
img.src = "image.jpg";
document.body.appendChild(img);
// css for tests
img { width:50%;height:50%; }
Solution 4
This uses the function and waits for it to complete.
http://jsfiddle.net/SN2t6/118/
function getMeta(url){
var r = $.Deferred();
$('<img/>').attr('src', url).load(function(){
var s = {w:this.width, h:this.height};
r.resolve(s)
});
return r;
}
getMeta("http://www.google.hr/images/srpr/logo3w.png").done(function(test){
alert(test.w + ' ' + test.h);
});
Solution 5
Combining promises & typescript typing:
/**
* Returns image dimensions for specified URL.
*/
export const getImageDimensions = (url: string): Promise<{width: number, height: number}> => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve({
width: img.width,
height: img.height,
});
img.onerror = (error) => reject(error);
img.src = url;
});
};
Usage:
try {
const {width, height} = await getImageDimensions(entry.NWS_IMAGE);
console.log(`Image dimensions: ${width}px x ${height}px`);
} catch (e) {
// Could not load image from specified URL
console.error(e);
}
Related videos on Youtube
Author by
JQueeeer
Updated on July 08, 2022Comments
-
JQueeeer almost 2 years
I only have a URL to an image. I need to determine the height and width of this image using only JavaScript. The image cannot be visible to the user on the page. How can I get its dimensions?
-
stecb about 13 years
-
Shadow The Kid Wizard about 13 yearsactually this answer is the only one really correct, as you have to wait until the image is loaded.
-
-
Adam Casey over 11 yearsI keep getting 0 for width and height, using this exact code.
-
Adam Casey over 11 yearsIt seems the image has to load, which makes sense.
-
Yaroslav Stavnichiy almost 11 yearsThe question was about getting image dimensions without showing image to the user. Setting image width and height attributes after image has been displayed makes absolutely no sense.
-
Shumii over 10 yearsadditional info - although this worked for me first time it was intermittent. I think the problem is because the image has not been downloaded. I fixed by running the code which uses the dimension in the onload event handler like so: img.onload = function () {};
-
JustAndrei about 9 yearsUnless you need to obtain the dimensions synchronously. In that case you just have to insert the image to the document (using an absolute position somewhere outside the viewport) - then the dimensions are available right after calling document.appendChild().
-
DavidDunham over 7 yearsWhy would this reusable function with deferrants be downvoted?!
-
bharatesh over 7 yearsThis code works, as long as the image is in the browser cache. Once cache is invalid or deleted. It won't work. So not really reliable.
-
user1702401 about 7 yearsThat's not working, since image is not loaded yet - image loading is done asynchronously, so you have to wait for load event.
-
Ajay Gaur almost 7 yearsWhy is
onload
before than setting the url of image? -
biomorgoth almost 7 years@AjayGaur because
onload
is a listener that will be called asynchronously if the image is loaded correctly. If you set the listener after setting the url, the image could load just before the code reachs setting the onload itself, resulting in the listener never being called. Using analogies, if you are serving yourself a glass with water, do you first pour the water and next you put the glass to fill it? Or do you first put the glass and then you pour the water in? -
Apolo over 5 yearsThis is a really bad answer / practice. The only way it can work is when you are using local/cached image or (maybe) one of the best internet connection in the world (not tested ;D). That means it will break in production. You should wait for the load event on the image before using img width/height.
-
Apolo over 5 years'using only JavaScript' and this is jQuery, I guess
-
krankuba almost 5 yearsYou get upvote from me although it is using jQuerry. The approach is that matters.
-
YakovL over 4 yearsplease correct this answer, it's better to have it look like a duplicate of Shumii's answer (although this one was posted muche earlier) than have a highly upvoted wrong/unreliable one. The
onload
handler should be used here -
Kamlesh over 4 yearsimg.naturalWidth and img.naturalHeight is correct answer
-
jahooma over 4 yearsThank you @Kamlesh I needed the natural dimensions.
-
mark_h over 3 yearsWhen is the onload function actually called? There is no reference to the img outside of the code in this example. I tried calling it straight after setting the img.src but always get 0 for width and height.
-
Shumii over 3 yearsI think it invoked when u set the src. Hence why u gotta setup the handler first so it will run when the src is set
-
Mehadi Hassan over 3 yearsBest answer for imported image in react
-
Jeremy Trpka over 3 yearsIs there a way to get the sizes outside the onload listener?
-
Shumii over 3 yearsYou can do it anywhere you want. But it might come back as 0 if its not loaded