How to validate image size, height, width and format before upload with jquery of PHP?

17,180

Solution 1

You can use jQuery to achieve this.

Demo code Once write a normal code input type ="file" and write down their id in below jQuery.

$(document).ready(function(){

 var _URL = window.URL || window.webkitURL;

 $('#file').change(function () {
  var file = $(this)[0].files[0];

  img = new Image();
  var imgwidth = 0;
  var imgheight = 0;
  var maxwidth = 640;
  var maxheight = 640;

  img.src = _URL.createObjectURL(file);
  img.onload = function() {
   imgwidth = this.width;
   imgheight = this.height;

   $("#width").text(imgwidth);
   $("#height").text(imgheight);
   if(imgwidth <= maxwidth && imgheight <= maxheight){

    var formData = new FormData();
    formData.append('fileToUpload', $('#file')[0].files[0]);

    $.ajax({
      url: 'upload_image.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      dataType: 'json',
      success: function (response) {
        if(response.status == 1){
          $("#prev_img").attr("src","upload/"+response.returnText);
          $("#prev_img").show();
          $("#response").text("Upload successfully");
        }else{
          $("#response").text(response.returnText);
        } 
      }
   });
  }else{
   $("#response").text("Image size must be "+maxwidth+"X"+maxheight);
  }
 };
 img.onerror = function() {

  $("#response").text("not a valid file: " + file.type);
 }

 });
});

Solution 2

As you have asked for jquery or PHP, I will suggest you to use php for this kind validation, Due to security point of view you must validate your uploaded file at server side. First to check if file is image you can use

mime_content_type or finfo_open()

After validating your file is image you can go for width and height

list($width, $height) = getimagesize($_FILES["fileToUpload"]); 

for size you use

$_FILES["fileToUpload"]["size"]

Hope combining this will resolve your issue.

Share:
17,180

Related videos on Youtube

james
Author by

james

Updated on June 04, 2022

Comments

  • james
    james almost 2 years

    I want to validate my image size, height, width and image format before upload with jquery or PHP. I found many answers, but I have not found all validate is together.

    Image format = png, Image size = 2mb, Image height = 800px, Image width= 600