Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine original size of image cross browser?

Is there a reliable, framework independent way of determining the physical dimensions of a <img src='xyz.jpg'> resized on the client side?

like image 877
Pekka Avatar asked Dec 22 '09 05:12

Pekka


People also ask

How do I change the original size of a picture?

One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels. For example, the original image is 640×960.


1 Answers

You have 2 options:

Option 1:

Remove the width and height attributes and read offsetWidth and offsetHeight

Option 2:

Create a JavaScript Image object, set the src, and read the width and height (you don't even have to add it to the page to do this).

function getImgSize(imgSrc) {     var newImg = new Image();      newImg.onload = function() {       var height = newImg.height;       var width = newImg.width;       alert ('The image size is '+width+'*'+height);     }      newImg.src = imgSrc; // this must be done AFTER setting onload } 

Edit by Pekka: As agreed in the comments, I changed the function to run on the ´onload´ event of the image. Otherwise, with big images, height and width would not return anything because the image was not loaded yet.

like image 186
Gabriel McAdams Avatar answered Sep 28 '22 10:09

Gabriel McAdams