How to Validate Image width and height Before upload using JavaScript

By adding file upload to the project, there may case arrives where you have to check image width and height before upload if you only allowed image files for uploading.

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

In this tutorial, I explain you with an example how to implement it. For uploading, I am using AJAX and PHP and done restriction 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 an 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 a new upload_image.php file and a upload folder for storing uploading images.

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

This file return a JSON object which contains upload status and responseText. If file uploaded successfully the responseText 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 within your project.

Sending AJAX request when size is within 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;
 box-shadow: 7px 10px 5px #888888;
 padding: 5px;
 }

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

#prev_img{
 display: none;
}

 

5. Demo

Browser an image.


 

6. Conclusion

Restricting Image is best if you want the user will only able 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.

Related Post

Spread the love

One Comment

  1. Divy Singh Rathore said:

    Thanks, It worked for me

    July 25, 2017
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *