Reputation: 11751
I am using JavaScript code to upload an image in FireBase/FireStore.
The core functionality already works, I can upload, but I also need to check the size of the image before uploading. And this is where I would be glad to get some help.
The following is my significant code. And the part between the lines:
// Trying to get the size:
and:
// End of trial code.
is not working.
upLdBtn.addEventListener('change', function(e) {
// Get the file.
var artWorkFile = e.target.files[0];
// Trying to get the size:
var img = new Image();
img.onload = function() {
window.alert('Size = ' + this.width + 'x' + this.height);
}
img.src = artWorkFile;
// End of trial code.
DoSomthingUseful(artWorkFile);
});
Upvotes: 0
Views: 708
Reputation: 11751
..........
Here is the finally working code:
upLdBtn.addEventListener('change', function(e) {
// Get the file.
var upLoadFile = e.target.files[0],
reader = new FileReader();
reader.onload = (function(elt) {
var image = new Image();
image.src = elt.target.result;
image.onload = function() {
if ((this.width != 100) || (this.height != 100)) {
window.alert('Only 100x100 is allowed !!');
return;
}
// Useful-Code-To-Perform-theUpLoad ....
..............
};
});
reader.readAsDataURL(upLoadFile);
});
This solution has found a very important help in the answer by Md. Amirozzaman.
Upvotes: 0
Reputation: 1125
First,we need to set upload img from input
to a img
container src,after from this img
element, we might get the original value of the image's width and height.
Here is the code snippet:
function setSrc(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#proImg').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function () {
setSrc(this);
setTimeout(getImgRatio,300);
});
function getImgRatio(){
var imgStyleProp = getComputedStyle(proImg);
var w =imgStyleProp.width;
var h =imgStyleProp.height;
console.log(w+"/"+h);
}
img{
width:initial;
height:initial;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="imgInp" required="required" class="custom-file-input">
<img id="proImg" src=""/>
Upvotes: 3
Reputation: 4383
You need to add this.style.height
and this.style.width
to access this property in CSS.
Upvotes: -1