Getting width & height of an image with filereader
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.
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);
};
});
fileChangeEventHeader(fileInput) {
const oFReader = new FileReader();
oFReader.readAsDataURL(fileInput.target.files[0]);
oFReader.onload = (event: any) => {
var image = new Image();
image.src = event.target.result;
image.onload = function () {
console.log(`width : ${image.width} px`, `height: ${image.height} px`);
};
};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<input type="file" name="profile_img" accept="image/*" (change)="fileChangeEventHeader($event)"
class="input-file">