[javascript] Check image width and height before upload with Javascript

I have a JPS with a form in which a user can put an image:

<div class="photo">
    <div>Photo (max 240x240 and 100 kb):</div>
    <input type="file" name="photo" id="photoInput" onchange="checkPhoto(this)"/>
</div>

I have written this js:

function checkPhoto(target) {
    if(target.files[0].type.indexOf("image") == -1) {
        document.getElementById("photoLabel").innerHTML = "File not supported";
        return false;
    }
    if(target.files[0].size > 102400) {
        document.getElementById("photoLabel").innerHTML = "Image too big (max 100kb)";
        return false;
    }
    document.getElementById("photoLabel").innerHTML = "";
    return true;
}

which works fine to check file type and size. Now I want to check image width and height but I cannot do it.
I have tried with target.files[0].width but I get undefined. With other ways I get 0.
Any suggestions?

This question is related to javascript image file-upload image-size

The answer is


The file is just a file, you need to create an image like so:

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

Demo: http://jsfiddle.net/4N6D9/1/

I take it you realize this is only supported in a few browsers. Mostly firefox and chrome, could be opera as well by now.

P.S. The URL.createObjectURL() method has been removed from the MediaStream interface. This method has been deprecated in 2013 and superseded by assigning streams to HTMLMediaElement.srcObject. The old method was removed because it is less safe, requiring a call to URL.revokeOjbectURL() to end the stream. Other user agents have either deprecated (Firefox) or removed (Safari) this feature feature.

For more information, please refer here.


I agree. Once it is uploaded to somewhere the user's browser can access then it is pretty easy to get the size. As you need to wait for the image to load you'll want to hook into the onload event for img.

var width, height;

var img = document.createElement("img");
img.onload = function() {
    // `naturalWidth`/`naturalHeight` aren't supported on <IE9. Fallback to normal width/height
    // The natural size is the actual image size regardless of rendering.
    // The 'normal' width/height are for the **rendered** size.

    width  = img.naturalWidth  || img.width;
    height = img.naturalHeight || img.height; 

    // Do something with the width and height
}

// Setting the source makes it start downloading and eventually call `onload`
img.src = "http://your.website.com/userUploadedImage.jpg";

function validateimg(ctrl) {

        var fileUpload = $("#txtPostImg")[0];


        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
        if (regex.test(fileUpload.value.toLowerCase())) {

            if (typeof (fileUpload.files) != "undefined") {

                var reader = new FileReader();

                reader.readAsDataURL(fileUpload.files[0]);
                reader.onload = function (e) {

                    var image = new Image();

                    image.src = e.target.result;
                    image.onload = function () {

                        var height = this.height;
                        var width = this.width;
                        console.log(this);
                        if ((height >= 1024 || height <= 1100) && (width >= 750 || width <= 800)) {
                            alert("Height and Width must not exceed 1100*800.");
                            return false;
                        }
                        alert("Uploaded image has valid Height and Width.");
                        return true;
                    };
                }
            } else {
                alert("This browser does not support HTML5.");
                return false;
            }
        } else {
            alert("Please select a valid Image file.");
            return false;
        }
    }

You can do the steps for previewing the image without showing it which is supported on all browsers. Following js code shows you how to check the width and height :

var file = e.target.files[0];
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
    var reader = new FileReader();
    reader.addEventListener("load", function () {
        var image = new Image();
        image.src = this.result as string;
        image.addEventListener('load', function () {
            console.log(`height: ${this.height}, width: ${this.width}`);
        });
                
    }, false);
            
    reader.readAsDataURL(file);
}

Based on Mozilla docs:

The readAsDataURL method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.

And the browser compatibility is listed too.


function uploadfile(ctrl) {
    var validate = validateimg(ctrl);

    if (validate) {
        if (window.FormData !== undefined) {
            ShowLoading();
            var fileUpload = $(ctrl).get(0);
            var files = fileUpload.files;


            var fileData = new FormData();


            for (var i = 0; i < files.length; i++) {
                fileData.append(files[i].name, files[i]);
            }


            fileData.append('username', 'Wishes');

            $.ajax({
                url: 'UploadWishesFiles',
                type: "POST",
                contentType: false,
                processData: false,
                data: fileData,
                success: function(result) {
                    var id = $(ctrl).attr('id');
                    $('#' + id.replace('txt', 'hdn')).val(result);

                    $('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();

                    HideLoading();
                },
                error: function(err) {
                    alert(err.statusText);
                    HideLoading();
                }
            });
        } else {
            alert("FormData is not supported.");
        }

    }

_x000D_
_x000D_
    const ValidateImg = (file) =>{_x000D_
        let img = new Image()_x000D_
        img.src = window.URL.createObjectURL(file)_x000D_
        img.onload = () => {_x000D_
            if(img.width === 100 && img.height ===100){_x000D_
                alert("Correct size");_x000D_
                return true;_x000D_
            }_x000D_
            alert("Incorrect size");_x000D_
            return true;_x000D_
        }_x000D_
    }
_x000D_
_x000D_
_x000D_


In my view the perfect answer you must required is

var reader = new FileReader();

//Read the contents of Image File.
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {

  //Initiate the JavaScript Image object.
  var image = new Image();

  //Set the Base64 string return from FileReader as source.
  image.src = e.target.result;

  //Validate the File Height and Width.
  image.onload = function () {
    var height = this.height;
    var width = this.width;
    if (height > 100 || width > 100) {
      alert("Height and Width must not exceed 100px.");
      return false;
    }
    alert("Uploaded image has valid Height and Width.");
    return true;
  };
};

Attach the function to the onchange method of the input type file /onchange="validateimg(this)"/

   function validateimg(ctrl) { 
        var fileUpload = ctrl;
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
        if (regex.test(fileUpload.value.toLowerCase())) {
            if (typeof (fileUpload.files) != "undefined") {
                var reader = new FileReader();
                reader.readAsDataURL(fileUpload.files[0]);
                reader.onload = function (e) {
                    var image = new Image();
                    image.src = e.target.result;
                    image.onload = function () {
                        var height = this.height;
                        var width = this.width;
                        if (height < 1100 || width < 750) {
                            alert("At least you can upload a 1100*750 photo size.");
                            return false;
                        }else{
                            alert("Uploaded image has valid Height and Width.");
                            return true;
                        }
                    };
                }
            } else {
                alert("This browser does not support HTML5.");
                return false;
            }
        } else {
            alert("Please select a valid Image file.");
            return false;
        }
    }

This is the easiest way to check the size

let img = new Image()
img.src = window.URL.createObjectURL(event.target.files[0])
img.onload = () => {
   alert(img.width + " " + img.height);
}

Check for specific size. Using 100 x 100 as example

let img = new Image()
img.src = window.URL.createObjectURL(event.target.files[0])
img.onload = () => {
   if(img.width === 100 && img.height === 100){
        alert(`Nice, image is the right size. It can be uploaded`)
        // upload logic here
        } else {
        alert(`Sorry, this image doesn't look like the size we wanted. It's 
   ${img.width} x ${img.height} but we require 100 x 100 size image.`);
   }                
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to file-upload

bootstrap 4 file input doesn't show the file name How to post a file from a form with Axios File Upload In Angular? How to set the max size of upload file The request was rejected because no multipart boundary was found in springboot Send multipart/form-data files with angular using $http File upload from <input type="file"> How to upload files in asp.net core? REST API - file (ie images) processing - best practices Angular - POST uploaded file

Examples related to image-size

XXHDPI and XXXHDPI dimensions in dp for images and icons in android Get file size, image width and height before upload Change image size via parent div Check image width and height before upload with Javascript Specifying width and height as percentages without skewing photo proportions in HTML