Martin Alderson Martin Alderson - 3 years ago 150
jQuery Question

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 =;

document.getElementById('profilepicturepreview').src =;
var imagepreview = document.getElementById('imgresizepreview');
handles: true,
enable: true,
aspectRatio: "1:1",
onSelectEnd: preview

Answer Source

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 =;

    image.onload = function() {
        // access image size here 

        $('#imgresizepreview, #profilepicturepreview').attr('src', this.src);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download