Reputation: 21
I'm using a function to Validate the size of an uploaded image. That works fine, now I also want to check if the image is wider than certain pixels (like 1280 pixels). But the var width still gives zero. I already tried to use outerwith, innerwidth and file.files[0].width;
function ValidateSize(file) {
var FileSize = file.files[0].size / 1024 / 1024; // in MB
var NewFilze = FileSize.toFixed(2);
var height = file.height;
var width = file.width;
if (FileSize > 13) {
alert("The file size of your picture (" + NewFilze + " MB) exceeds the maximum allowed filesize (12,5 MB). Still problems with resizing your pictures? Use for example www.imageresize.org.");
}else if(width < 1280){
alert("The width of your image (" + width + " pixels) is lower than the required minimum width (1280 pixels)");
}else{
}
}
Thanks in advance
Upvotes: 0
Views: 539
Reputation: 2288
You need to convert the file into an image :
Here is an example of How to convert a file to img to get width and hight :
function getSize(file) {
const img = new Image();
var file = file.files[0];
var reader = new FileReader();
reader.addEventListener("load", function() {
img.src = reader.result;
}, false);
const promise = new Promise((resolve, reject) => {
img.onload = () => {
console.log(img.naturalWidth, img.naturalHeight);
resolve([img.naturalWidth, img.naturalHeight]);
};
});
if (file) {
reader.readAsDataURL(file);
}
return promise.then(res => [img.naturalWidth, img.naturalHeight]);
}
You can do some changements to make it work for your case. Good luck
Upvotes: 2
Reputation: 832
Without being able to test this on my own I would suggest trying something like the following:
function ValidateSize(file) {
var FileSize = file.files[0].size / 1024 / 1024; // in MB
var NewFilze = FileSize.toFixed(2);
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var height = this.height;
var width = this.width;
if (FileSize > 13) {
alert("The file size of your picture (" + NewFilze + " MB) exceeds the maximum allowed filesize (12,5 MB). Still problems with resizing your pictures? Use for example www.imageresize.org.");
}else if(width < 1280){
alert("The width of your image (" + width + " pixels) is lower than the required minimum width (1280 pixels)");
}else{
}
}
I should note this is untested and dependent on your js running on some browser (ideally chrome or FF). If it is server side I think visibleman is linked the best answer.
Good luck and happy hacking!!
Credit where its due SO post where I got the image code
Upvotes: 1