Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
113
rated 0 times [  114] [ 1]  / answers: 1 / hits: 70839  / 11 Years ago, tue, march 19, 2013, 12:00:00

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');
};

More From » dom

 Answers
6

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);
};
});

[#79503] Monday, March 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
diontajm

Total Points: 391
Total Questions: 104
Total Answers: 104

Location: Netherlands
Member since Mon, Jun 7, 2021
3 Years ago
;