Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting width & height of an image with filereader

I am building an image resize/crop, and I'd like to show a live preview after they've edited it in a modal (bootstrap). This should work, I believe, but I just get 0 in console.log. This requires feeding the width and the height of the original image into another script (which I'll do after, just need them in console.log/a variable for now)

function doProfilePictureChangeEdit(e) {     var files = document.getElementById('fileupload').files[0];     var reader = new FileReader();     reader.onload = (function(theFile) {         document.getElementById('imgresizepreview').src = theFile.target.result;          document.getElementById('profilepicturepreview').src = theFile.target.result;       }     );     reader.readAsDataURL(files);     var imagepreview = document.getElementById('imgresizepreview');     console.log(imagepreview.offsetWidth);     $('img#imgresizepreview').imgAreaSelect({         handles: true,         enable: true,         aspectRatio: "1:1",         onSelectEnd: preview     });     $('#resizeprofilepicturemodal').modal('show');     }; 
like image 644
Martin Alderson Avatar asked Mar 19 '13 03:03

Martin Alderson


People also ask

How do you find the width of an element?

The offsetWidth property returns the viewable width of an element (in pixels) including padding, border and scrollbar, but not the margin. The offsetWidth property is read-only.

How do I find the width of a div?

With jQuery, you can use the . width() method to get the div container's content width.

How is CSS width calculated?

Here the dimensions of the element are calculated as: width = border + padding + width of the content, and height = border + padding + height of the content.


2 Answers

You have to wait for the image to load. Try handling the element inside .onload.

I've also simplified the process of setting the source of the two elements to how you should be doing it (with jQuery).

reader.onload = (function(theFile) {      var image = new Image();     image.src = theFile.target.result;      image.onload = function() {         // access image size here          console.log(this.width);          $('#imgresizepreview, #profilepicturepreview').attr('src', this.src);     }; }); 
like image 99
Austin Brunkhorst Avatar answered Sep 22 '22 13:09

Austin Brunkhorst


For me the solution of Austin didn't work, so I present the one worked for me:

var reader = new FileReader;  reader.onload = function() {     var image = new Image();      image.src = reader.result;      image.onload = function() {         alert(image.width);     };  };  reader.readAsDataURL(this.files[0]); 

And if you find that assignment image.src = reader.result; takes place after image.onload a bit wired, I think so too.

like image 43
andilabs Avatar answered Sep 24 '22 13:09

andilabs