Как получить размер изображения html

How to get the image size (height & width) using JavaScript

Most of the answers below just get the style width and height, not the actual image’s width and height. Use imgElement.naturalWidth and imgElement.naturalHeight for getting width and height.

Regardless of whether you want to use Javascript or jQuery it is essential that the image is visible in the browser. In practice, neither the image nor the parent elements must have the rule display:none; .

33 Answers 33

You can programmatically get the image and check the dimensions using JavaScript.

const img = new Image(); img.onload = function() < alert(this.width + 'x' + this.height); >img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

This can be useful if the image is not a part of the markup.

clientWidth and clientHeight are DOM properties that show the current in-browser size of the inner dimensions of a DOM element (excluding margin and border). So in the case of an IMG element, this will get the actual dimensions of the visible image.

var img = document.getElementById('imageid'); //or however you get a handle to the IMG var width = img.clientWidth; var height = img.clientHeight; 

Also (in addition to Rex and Ian’s answers) there is:

imageElement.naturalHeight 

These provide the height and width of the image file itself (rather than just the image element).

Thank you. I was having an issue getting the width and height of some images before inserting them into the database. For some reason, the image would be 0x0. Adding this in place of «clientWidth» and «clientHeight» I was able to get rid of the bug. (I hope). Will have to wait and see what happens in the future, as I thought the other way was working as well when it started sticking 0x0. This does as well, but once the page is refreshed it inserts the correct dimensions. Thank you.

Читайте также:  Java and microsoft sql server

If you are using jQuery and you are requesting image sizes you have to wait until they load or you will only get zeroes.

@AndersLindén — see thel ink that Akseli added for the load event. There is a specific section devoted to images. The technical answer is «no,» but in practice I’ve never had a problem with our sites that use this method.

Using clientWidth and clientHeight is, I think, now obsolete.

I have done some experiments with HTML5, to see which values actually get returned.

First of all, I used a program called Dash to get an overview of the image API.

It states that height and width are the rendered height/width of the image and that naturalHeight and naturalWidth are the intrinsic height/width of the image (and are HTML5 only).

I used an image of a beautiful butterfly, from a file with height 300 and width 400. And this JavaScript code:

var img = document.getElementById("img1"); console.log(img.height, img.width); console.log(img.naturalHeight, img.naturalWidth); console.log($("#img1").height(), $("#img1").width()); 

Then I used this HTML, with inline CSS for the height and width.

/* Image element */ height == 300 width == 400 naturalHeight == 300 naturalWidth == 400 /* jQuery */ height() == 120 width() == 150 /* Actual rendered size */ 120 150 

I then changed the HTML to the following:

I.e., using height and width attributes rather than inline styles.

/* Image element */ height == 90 width == 115 naturalHeight == 300 naturalWidth == 400 /* jQuery */ height() == 90 width() == 115 /* Actual rendered size */ 90 115 

I then changed the HTML to the following:

  

I.e., using both attributes and CSS, to see which takes precedence.

/* Image element */ height == 90 width == 115 naturalHeight == 300 naturalWidth == 400 /* jQuery */ height() == 120 width() == 150 /* Actual rendered size */ 120 150 

«which I think is now obsolete» What do you mean? Do you mean deprecated? Or removed? And do you _know? «I think» is not very reassuring if I am going to depend on an answer.

var imgWidth = $("#imgIDWhatever").width(); 

The thing all other have forgot is that you can’t check image size before it loads. When the author checks all of posted methods it will work probably only on localhost.

Since jQuery could be used here, remember that the ‘ready’ event is fired before images are loaded. $(‘#xxx’).width() and .height() should be fired in the onload event or later.

You can only really do this using a callback of the load event as the size of the image is not known until it has actually finished loading. Something like the code below.

var imgTesting = new Image(); function CreateDelegate(contextObject, delegateMethod) < return function() < return delegateMethod.apply(contextObject, arguments); >> function imgTesting_onload() < alert(this.width + " by " + this.height); >imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload); imgTesting.src = 'yourimage.jpg'; 

Let’s combine everything we learned here into one simple function ( imageDimensions() ). It uses promises.

// helper to get dimensions of an image const imageDimensions = file => new Promise((resolve, reject) => < const img = new Image() // the following handler will fire after a successful loading of the image img.onload = () => < const < naturalWidth: width, naturalHeight: height >= img resolve(< width, height >) > // and this handler will fire if there was an error with the image (like if it's not really an image or a corrupted one) img.onerror = () => < reject('There was some problem with the image.') >img.src = URL.createObjectURL(file) >) // here's how to use the helper const getInfo = async ( < target: < files >>) => < const [file] = files try < const dimensions = await imageDimensions(file) console.info(dimensions) >catch(error) < console.error(error) >>
 Select an image:  
It works offline.

thanks for this code, but it returns 0 for width and height in firefox for SVG images without defined width and height attributes (eg, ones with only viewBox set).

To get the natural height and width:

document.querySelector("img").naturalHeight; document.querySelector("img").naturalWidth;

And if you want to get style height and width:

document.querySelector("img").offsetHeight; document.querySelector("img").offsetWidth;

Assuming, we want to get image dimensions of

// Query after all the elements on the page have loaded. // Or, use `onload` on a particular element to check if it is loaded. document.addEventListener('DOMContentLoaded', function () < var el = document.getElementById("an-img"); console.log(< "naturalWidth": el.naturalWidth, // Only on HTMLImageElement "naturalHeight": el.naturalHeight, // Only on HTMLImageElement "offsetWidth": el.offsetWidth, "offsetHeight": el.offsetHeight >); >) 

Natural Dimensions

el.naturalWidth and el.naturalHeight will get us the natural dimensions, the dimensions of the image file.

Layout Dimensions

el.offsetWidth and el.offsetHeight will get us the dimensions at which the element is rendered on the document.

Just upvote the existing answers that provide helpful content; don’t copy from several of them into a new one; you’re just duplicating content then.

This answer was exactly what I was looking for (in jQuery):

var imageNaturalWidth = $('image-selector').prop('naturalWidth'); var imageNaturalHeight = $('image-selector').prop('naturalHeight'); 

I think I improved the source code to be able to let the image load before trying to find out its properties. Otherwise, it will display ‘0 * 0’, because the next statement would have been called before the file was loaded into the browser. It requires jQuery.

function getImgSize(imgSrc) < var newImg = new Image(); newImg.src = imgSrc; var height = newImg.height; var width = newImg.width; p = $(newImg).ready(function() < return ; >); alert (p[0]['width'] + " " + p[0]['height']); > 

I thought this might be helpful to some who are using JavaScript and/or TypeScript in 2019.

I found the following, as some have suggested, to be incorrect:

let img = new Image(); img.onload = function() < console.log(this.width, this.height) // Error: undefined is not an object >; img.src = "http://example.com/myimage.jpg"; 
let img = new Image(); img.onload = function() < console.log(img.width, img.height) >; img.src = "http://example.com/myimage.jpg"; 

Use img , not this , in the onload function.

img.src above has a typo, should be » not : I tried to edit this but can’t because: «Edits must be at least 6 characters; is there something else to improve in this post?» Otherwise a very simple solution that works perfectly!

Thanks @user2677034 for noticing. I didn’t see that. I’ll blame Apple’s keyboard. Just kidding. It was probably my fault. ;P

Before using the real image size, you should load the source image. If you use the jQuery framework, you can get the real image size in a simple way.

Example Code-

 
$height = $('#image_id').height(); $width = $('#image_id').width(); 

My two cents in jQuery

Disclaimer: This does not necessarily answer this question, but broadens our capabilities. It was tested and working in jQuery 3.3.1

  1. You have the image URL/path and you want to get the image width and height without rendering it on the DOM,
  2. Before rendering image on the DOM, you need to set the offsetParent node or image div wrapper element to the image width and height, to create a fluid wrapper for different image sizes, i.e., when clicking a button to view image on a modal/lightbox
// image path const imageUrl = '/path/to/your/image.jpg' // Create dummy image to get real width and height $('Как получить размер изображения html').attr("src", imageUrl).on('load', function()< const realWidth = this.width; const realHeight = this.height; alert(`Original width: $, Original height: $`); >) 

Recently I had the same issue for an error in the flex slider. The first image’s height was set smaller due to the loading delay. I tried the following method for resolving that issue and it’s worked.

// Create an image with a reference id. Id shall // be used for removing it from the DOM later. var tempImg = $(''); // If you want to get the height with respect to any specific width you set. // I used window width here. tempImg.css('width', window.innerWidth); tempImg[0].onload = function () < $(this).css('height', 'auto').css('display', 'none'); var imgHeight = $(this).height(); // Remove it if you don't want this image anymore. $('#testImage').remove(); >// Append to body $('body').append(tempImg); // Set an image URL. I am using an image which I got from Google. tempImg[0].src ='http://aspo.org/wp-content/uploads/strips.jpg'; 

This will give you the height with respect to the width you set rather than original width or Zero.

Nicky De Maeyer asked for a background picture; I simply get it from the CSS content and replace the «url()»:

var div = $('#my-bg-div'); var url = div.css('background-image').replace(/^url\(\'?(.*)\'?\)$/, '$1'); var img = new Image(); img.src = url; console.log('img:', img.width + 'x' + img.height); // Zero, image not yet loaded console.log('div:', div.width() + 'x' + div.height()); img.onload = function() < console.log('img:', img.width + 'x' + img.height, (img.width/div.width())); >

I never understood the use of regexp for this when using jQuery. Since jQuery will normalize the attribute for you you get away just fine by using s.substr(4,s.length-5) , it’s at least easier on the eyes 😉

You can apply the onload handler property when the page loads in JavaScript or jQuery like this:

This is an alternative answer for Node.js. That isn’t likely what the OP meant, but it could come in handy and seems to be in the scope of the question.

This is a solution with Node.js, and the example uses the Next.js framework, but it would work with any Node.js framework. It uses the probe-image-size NPM package to resolve the image attributes from the server side.

Example use case: I used the below code to resolve the size of an image from an Airtable Automation script, which calls my own analyzeImage API and returns the image’s props.

import < NextApiRequest, NextApiResponse, >from 'next'; import probe from 'probe-image-size'; export const analyzeImage = async (req: NextApiRequest, res: NextApiResponse): Promise => < try < const result = await probe('http://www.google.com/intl/en_ALL/images/logo.gif'); res.json(result); >catch (e) < res.json(< error: true, message: process.env.NODE_ENV === 'production' ? undefined : e.message, >); > >; export default analyzeImage; 

In my case, I have a File type (that is guaranteed to be an image), and I want the image dimensions without loading it on the DOM.

General strategy: Convert File to ArrayBuffer → Convert ArrayBuffer to a base64 string → use this as the image source with an Image class → use naturalHeight & naturalWidth to get dimensions.

const fr = new FileReader(); fr.readAsArrayBuffer(image); // Image the 'File' object fr.onload = () => < const arrayBuffer: ArrayBuffer = fr.result as ArrayBuffer; // Convert to base64. String.fromCharCode can hit a stack overflow error if you pass // the entire arrayBuffer in, and iteration gets around this let binary = ''; const bytes = new Uint8Array(arrayBuffer); bytes.forEach(b =>binary += String.fromCharCode(b)); const base64Data = window.btoa(binary); // Create an image object. Note, a default width/height MUST be given to the constructor (per // the documentation) or naturalWidth/Height will always return 0. const imageObj = new Image(100, 100); imageObj.src = `data:$;base64,$`; imageObj.onload = () => < console.log(imageObj.naturalWidth, imageObj.naturalHeight); >> 

This allows you to get the image dimensions and aspect ratio all from a File without rendering it. It can easily convert the onload functions to RxJS Observables using fromEvent for a better async experience:

// fr is the file reader, and this is the same as fr.onload = () => < . >fromEvent(fr, 'load') 

Источник

Оцените статью