How to Validate Image width and height Before upload using JavaScript

While allowing users to upload files then there may be a case arrives where you have to restrict image width and height before upload.

This is very common in Job Application Forms where the user can only upload its profile photo of given dimensions other it’s not uploaded.

In this tutorial, I explain with an example how you can implement it. For uploading, I am using AJAX and PHP and done restrictions with JavaScript.

How to Validate Image width and height Before upload using JavaScript


Contents

  1. HTML
  2. PHP
  3. jQuery
  4. CSS
  5. Demo
  6. Conclusion

1. HTML

Create a file element and a <div > container with <img > to show image preview after upload.

Completed Code 

<div class='container'>
  <form action="multipart/form-data">
    <div id="preview"><img src="" id="prev_img" width="100%" height='100%'></div>
    <input type="file" name="file" id="file">
    <br/>
    Width: <span id='width'></span><br/>
    Height: <span id='height'></span>
    <h3 id='response'></h3>
  </form>
</div>

2. PHP

Create upload_image.php file and a upload folder for storing uploading images.

Within this check the file is an image or not if it is then upload it using the move_uploaded_file() function.

This file returns a JSON object which contains upload status and returnText.

If the file uploaded successfully then the returnText have a name of an image that is used in jQuery for displaying the image preview.

Completed Code

<?php
$target_dir = "upload/";
$returnText = "";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

// Check image format
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
 && $imageFileType != "gif" ) {
     $returnText = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}

if ($uploadOk == 0) {
    $returnText = "Sorry, your file was not uploaded.";
} else {
    // if everything is ok, try to upload file
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
          $returnText = basename( $_FILES["fileToUpload"]["name"]);
    } else {
          $uploadOk = 0;
          $returnText = "Sorry, there was an error uploading your file.";
    }
}

echo json_encode(array("status"=>$uploadOk,"returnText"=>$returnText));
?>

3. jQuery

When change event trigger on file element then gets the uploading image width and height using Image object.

I set the value of max-width to 640 and max-height to 640 which you can change while implementing in your project.

Send AJAX request when size is within the required range.

On success setting <img> element source if image upload successfully.

Completed Code

$(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);
            }

     });
});

4. CSS

.container{
     border: 1px solid black;
     width: 350px;
     padding: 5px;
}

#preview{
     width: 100px;
     height: 100px;
     margin: 0 auto;
     border: 1px solid gray;
     border-radius: 3px;
}

#prev_img{
     display: none;
}

5. Demo

View Demo


6. Conclusion

With this, you can restrict the user to upload a fixed dimension or within the available range Image.

For restriction using Image object in JavaScript from this get image width and height which use to check.