How to Validate Image width and height Before upload using JavaScript

Adding file upload functionality to your project there may case arrives where you have to check Image dimensions before upload.

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

What in the tutorial ?

In this tutorial, I explain you with an example How to implement it. For uploading, I am using AJAX and PHP and done restriction using JavaScript.

How to Validate image width and height before upload using JavaScript


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



In HTML, create a file element and <div> with id=’preview’ for showing preview of image after upload.

Completed Code 

<!doctype html>
  <title>How to Validate image width and height before upload using JavaScript</title>
  <link href='style.css' rel='stylesheet' type='text/css'>
  <script src='jquery-1.12.0.min.js' type='text/javascript'></script>
  <script src='script.js' type='text/javascript'></script>
  <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">
    Width: <span id='width'></span><br/>
    Height: <span id='height'></span>
    <h3 id='response'></h3>


2. PHP

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

Within this checking uploading 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 showing the image in <div>.

Completed Code

$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

Create a new script.js file from their handling AJAX operation and showing the preview of an image after upload.

When file element change event trigger 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


 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;
   if(imgwidth <= maxwidth && imgheight <= maxheight){
    var formData = new FormData();
    formData.append('fileToUpload', $('#file')[0].files[0]);

      url: 'upload_image.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      dataType: 'json',
      success: function (response) {
        if(response.status == 1){
          $("#response").text("Upload successfully");
   $("#response").text("Image size must be "+maxwidth+"X"+maxheight);
 img.onerror = function() {
  $("#response").text("not a valid file: " + file.type);



4. CSS

 border: 1px solid black;
 width: 350px;
 box-shadow: 7px 10px 5px #888888;
 padding: 5px;

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

 display: none;


5. Final Output

Working result after all implementation.


6. Conclusion

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

Spread the love

Related Post

Be First to Comment

Leave a Reply

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