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'); };
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.
With jQuery, you can use the . width() method to get the div container's content width.
Here the dimensions of the element are calculated as: width = border + padding + width of the content, and height = border + padding + height of the content.
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); }; });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With