Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Image Dimensions using Javascript File API

I require to generate a thumbnail of an image in my Web Application. I make use of the Html 5 File API to generate the thumbnail.

I made use of the examples from the below URL to generate the thumbnails.

http://www.html5rocks.com/en/tutorials/file/dndfiles/

I am successfully able to generate the thumbnails. The problem that I have is I am able to generate thumbnail only by using a static size. Is there a way to get the file dimensions from the selected file and then create the Image object?

like image 854
Abishek Avatar asked Sep 18 '11 08:09

Abishek


People also ask

How do you get the image width and height using JS?

Answer: Use the JavaScript clientWidth property You can simply use the JavaScript clientWidth property to get the current width and height of an image. This property will round the value to an integer.

How do I find the dimensions of a photo?

You can also right-click on an image & choose properties from the drop-down menu. A new window will appear with several tabs. You'll click the details tab, and there you'll find you image size and dimensions.

How can get image width and height in jquery?

var imageWidth = $(Imgsize). width(); alert(imageWidth);


2 Answers

Yes, read the file as a data URL and pass that data URL to the src of an Image: http://jsfiddle.net/pimvdb/eD2Ez/2/.

var fr = new FileReader;  fr.onload = function() { // file is loaded     var img = new Image;      img.onload = function() {         alert(img.width); // image is loaded; sizes are available     };      img.src = fr.result; // is the data URL because called with readAsDataURL };  fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating 
like image 125
pimvdb Avatar answered Oct 01 '22 13:10

pimvdb


Or use an object URL: http://jsfiddle.net/8C4UB/

var url = URL.createObjectURL(this.files[0]); var img = new Image;  img.onload = function() {     alert(img.width);     URL.revokeObjectURL(img.src); };  img.src = url; 
like image 35
letmaik Avatar answered Oct 01 '22 13:10

letmaik