[javascript] Get file size, image width and height before upload

How can I get the file size, image height and width before upload to my website, with jQuery or JavaScript?

This question is related to javascript jquery html dimensions image-size

The answer is


If you can use the jQuery validation plugin you can do it like so:

Html:

<input type="file" name="photo" id="photoInput" />

JavaScript:

$.validator.addMethod('imagedim', function(value, element, param) {
  var _URL = window.URL;
        var  img;
        if ((element = this.files[0])) {
            img = new Image();
            img.onload = function () {
                console.log("Width:" + this.width + "   Height: " + this.height);//this will give you image width and height and you can easily validate here....

                return this.width >= param
            };
            img.src = _URL.createObjectURL(element);
        }
});

The function is passed as ab onload function.

The code is taken from here


A working jQuery validate example:

   $(function () {
        $('input[type=file]').on('change', function() {
            var $el = $(this);
            var files = this.files;
            var image = new Image();
            image.onload = function() {
                $el
                    .attr('data-upload-width', this.naturalWidth)
                    .attr('data-upload-height', this.naturalHeight);
            }

            image.src = URL.createObjectURL(files[0]);
        });

        jQuery.validator.unobtrusive.adapters.add('imageminwidth', ['imageminwidth'], function (options) {
            var params = {
                imageminwidth: options.params.imageminwidth.split(',')
            };

            options.rules['imageminwidth'] = params;
            if (options.message) {
                options.messages['imageminwidth'] = options.message;
            }
        });

        jQuery.validator.addMethod("imageminwidth", function (value, element, param) {
            var $el = $(element);
            if(!element.files && element.files[0]) return true;
            return parseInt($el.attr('data-upload-width')) >=  parseInt(param["imageminwidth"][0]);
        });

    } (jQuery));

Here is a pure JavaScript example of picking an image file, displaying it, looping through the image properties, and then re-sizing the image from the canvas into an IMG tag and explicitly setting the re-sized image type to jpeg.

If you right click the top image, in the canvas tag, and choose Save File As, it will default to a PNG format. If you right click, and Save File as the lower image, it will default to a JPEG format. Any file over 400px in width is reduced to 400px in width, and a height proportional to the original file.

HTML

<form class='frmUpload'>
  <input name="picOneUpload" type="file" accept="image/*" onchange="picUpload(this.files[0])" >
</form>

<canvas id="cnvsForFormat" width="400" height="266" style="border:1px solid #c3c3c3"></canvas>
<div id='allImgProperties' style="display:inline"></div>

<div id='imgTwoForJPG'></div>

SCRIPT

<script>

window.picUpload = function(frmData) {
  console.log("picUpload ran: " + frmData);

var allObjtProperties = '';
for (objProprty in frmData) {
    console.log(objProprty + " : " + frmData[objProprty]);
    allObjtProperties = allObjtProperties + "<span>" + objProprty + ": " + frmData[objProprty] + ", </span>";
};

document.getElementById('allImgProperties').innerHTML = allObjtProperties;

var cnvs=document.getElementById("cnvsForFormat");
console.log("cnvs: " + cnvs);
var ctx=cnvs.getContext("2d");

var img = new Image;
img.src = URL.createObjectURL(frmData);

console.log('img: ' + img);

img.onload = function() {
  var picWidth = this.width;
  var picHeight = this.height;

  var wdthHghtRatio = picHeight/picWidth;
  console.log('wdthHghtRatio: ' + wdthHghtRatio);

  if (Number(picWidth) > 400) {
    var newHeight = Math.round(Number(400) * wdthHghtRatio);
  } else {
    return false;
  };

    document.getElementById('cnvsForFormat').height = newHeight;
    console.log('width: 400  h: ' + newHeight);
    //You must change the width and height settings in order to decrease the image size, but
    //it needs to be proportional to the original dimensions.
    console.log('This is BEFORE the DRAW IMAGE');
    ctx.drawImage(img,0,0, 400, newHeight);

    console.log('THIS IS AFTER THE DRAW IMAGE!');

    //Even if original image is jpeg, getting data out of the canvas will default to png if not specified
    var canvasToDtaUrl = cnvs.toDataURL("image/jpeg");
    //The type and size of the image in this new IMG tag will be JPEG, and possibly much smaller in size
    document.getElementById('imgTwoForJPG').innerHTML = "<img src='" + canvasToDtaUrl + "'>";
};
};

</script>

Here is a jsFiddle:

jsFiddle Pick, display, get properties, and Re-size an image file

In jsFiddle, right clicking the top image, which is a canvas, won't give you the same save options as right clicking the bottom image in an IMG tag.


Demo

Not sure if it is what you want, but just simple example:

var input = document.getElementById('input');

input.addEventListener("change", function() {
    var file  = this.files[0];
    var img = new Image();

    img.onload = function() {
        var sizes = {
            width:this.width,
            height: this.height
        };
        URL.revokeObjectURL(this.src);

        console.log('onload: sizes', sizes);
        console.log('onload: this', this);
    }

    var objectURL = URL.createObjectURL(file);

    console.log('change: file', file);
    console.log('change: objectURL', objectURL);
    img.src = objectURL;
});

As far as I know there is not an easy way to do this since Javascript/JQuery does not have access to the local filesystem. There are some new features in html 5 that allows you to check certain meta data such as file size but I'm not sure if you can actually get the image dimensions.

Here is an article I found regarding the html 5 features, and a work around for IE that involves using an ActiveX control. http://jquerybyexample.blogspot.com/2012/03/how-to-check-file-size-before-uploading.html


So I started experimenting with the different things that FileReader API had to offer and could create an IMG tag with a DATA URL.

Drawback: It doesn't work on mobile phones, but it works fine on Google Chrome.

_x000D_
_x000D_
$('input').change(function() {_x000D_
    _x000D_
    var fr = new FileReader;_x000D_
    _x000D_
    fr.onload = function() {_x000D_
        var img = new Image;_x000D_
        _x000D_
        img.onload = function() { _x000D_
//I loaded the image and have complete control over all attributes, like width and src, which is the purpose of filereader._x000D_
            $.ajax({url: img.src, async: false, success: function(result){_x000D_
              $("#result").html("READING IMAGE, PLEASE WAIT...")_x000D_
              $("#result").html("<img src='" + img.src + "' />");_x000D_
                console.log("Finished reading Image");_x000D_
          }});_x000D_
        };_x000D_
        _x000D_
        img.src = fr.result;_x000D_
    };_x000D_
    _x000D_
    fr.readAsDataURL(this.files[0]);_x000D_
    _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" accept="image/*" capture="camera">_x000D_
<div id='result'>Please choose a file to view it. <br/>(Tested successfully on Chrome - 100% SUCCESS RATE)</div>
_x000D_
_x000D_
_x000D_

(see this on a jsfiddle at http://jsfiddle.net/eD2Ez/530/)
(see the original jsfiddle that i added upon to at http://jsfiddle.net/eD2Ez/)


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 jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to dimensions

Get file size, image width and height before upload Get image dimensions Numpy array dimensions How to get screen dimensions as pixels in Android Total width of element (including padding and border) in jQuery

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