jQuery Gets the width height and size of a picture in an file control

  • 2021-07-09 06:37:17
  • OfStack

Problem

How to judge the width, height and size of the pictures uploaded in the input file form?

Solutions

At this time, the picture has not been really uploaded, nor is it displayed on the page, so it cannot be used $(“#id”).width(),$(“#id”).height() This way.

Find a way to get the width and height of input file picture file in Stack Overflow:


var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
  var file, img;
  if ((file = this.files[0])) {
    img = new Image();
    img.onload = function () {
      alert(this.width + " " + this.height);
    };
    img.src = _URL.createObjectURL(file);
  }
});

Found that it can be used, only tested in Firefox, and the compatibility of other browsers is unknown. Because it is used in the background, it is encapsulated under 1 regardless of compatibility for the time being.

I perfected this function by 1 to get the width, height and size of input file picture, as follows:


// Get input Picture width, height and size 
function getImageWidthAndHeight(id, callback) {
  var _URL = window.URL || window.webkitURL;
  $("#" + id).change(function (e) {
    var file, img;
    if ((file = this.files[0])) {
      img = new Image();
      img.onload = function () {
        callback && callback({"width": this.width, "height": this.height, "filesize": file.size});
      };
      img.src = _URL.createObjectURL(file);
    }
  });
}

Here, a callback method is used. The parameters of the callback method are this json object, including width, height and size. In jQuery, it is called as follows:


(function () {
  // Omit other codes 
  getImageWidthAndHeight('image_file', function (obj) {
   if (obj.width != 843 || obj.height != 1038) {
    $.messager.alert(' Operation tips ', ' Pop-up picture width and height must be 843*1038px');
   }
  });
})(jQuery)

Ok, this is OK. The above is all the contents of jQuery to obtain the width, height and size of intput file pictures. I believe the contents of this article will be very helpful for everyone to use jQuery and upload pictures at ordinary times.


Related articles: