Warm tip: This article is reproduced from stackoverflow.com, please click
javascript

Image.width gives 0

发布于 2020-03-27 15:39:59

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

Questioner
Glenn S
Viewed
17
FujiRoyale 2020-01-31 16:45

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