How to Preview Image, get file size, image height

2018-12-31 07:04发布

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

7条回答
时光乱了年华
2楼-- · 2018-12-31 07:06

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));
查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 07:09

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

查看更多
荒废的爱情
4楼-- · 2018-12-31 07:11

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;
});
查看更多
不流泪的眼
5楼-- · 2018-12-31 07:12

HTML5 and the File API

Here's the uncommented working code snippet example:

window.URL    = window.URL || window.webkitURL;
var elBrowse  = document.getElementById("browse"),
    elPreview = document.getElementById("preview"),
    useBlob   = false && window.URL; // set to `true` to use Blob instead of Data-URL

function readImage (file) {
  var reader = new FileReader();

  reader.addEventListener("load", function () {
    var image  = new Image();
    
    image.addEventListener("load", function () {
      var imageInfo = file.name +' '+
          image.width +'×'+
          image.height +' '+
          file.type +' '+
          Math.round(file.size/1024) +'KB';

      // Show image and info
      elPreview.appendChild( this );
      elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');

      if (useBlob) {
        // Free some memory
        window.URL.revokeObjectURL(image.src);
      }
    });
    image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
  });

  reader.readAsDataURL(file);  
}


elBrowse.addEventListener("change", function() {

  var files = this.files, errors = "";

  if (!files) {
    errors += "File upload not supported by your browser.";
  }

  if (files && files[0]) {

    for(var i=0; i<files.length; i++) {
      var file = files[i];
      
      if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
        readImage( file ); 
      } else {
        errors += file.name +" Unsupported Image extension\n";  
      }
      
    }
  }

  // Handle errors
  if (errors) {
    alert(errors); 
  }

});
#preview img{height:100px;}
<input id="browse" type="file"  multiple />
<div id="preview"></div>


Using an input and a div for the images preview area

<input id="browse" type="file" multiple>
<div id="preview"></div>

let's also use a CSS to keep the resulting images a reasonable height:

#preview img{ height:100px; }

JavaScript:

window.URL    = window.URL || window.webkitURL;
var elBrowse  = document.getElementById("browse"),
    elPreview = document.getElementById("preview"),
    useBlob   = false && window.URL; // Set to `true` to use Blob instead of Data-URL

// 2.
function readImage (file) {

  // Create a new FileReader instance
  // https://developer.mozilla.org/en/docs/Web/API/FileReader
  var reader = new FileReader();

  // Once a file is successfully readed:
  reader.addEventListener("load", function () {

    // At this point `reader.result` contains already the Base64 Data-URL
    // and we've could immediately show an image using
    // `elPreview.insertAdjacentHTML("beforeend", "<img src='"+ reader.result +"'>");`
    // But we want to get that image's width and height px values!
    // Since the File Object does not hold the size of an image
    // we need to create a new image and assign it's src, so when
    // the image is loaded we can calculate it's width and height:
    var image  = new Image();
    image.addEventListener("load", function () {

      // Concatenate our HTML image info 
      var imageInfo = file.name    +' '+ // get the value of `name` from the `file` Obj
          image.width  +'×'+ // But get the width from our `image`
          image.height +' '+
          file.type    +' '+
          Math.round(file.size/1024) +'KB';

      // Finally append our created image and the HTML info string to our `#preview` 
      elPreview.appendChild( this );
      elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');

      // If we set the variable `useBlob` to true:
      // (Data-URLs can end up being really large
      // `src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAA...........etc`
      // Blobs are usually faster and the image src will hold a shorter blob name
      // src="blob:http%3A//example.com/2a303acf-c34c-4d0a-85d4-2136eef7d723"
      if (useBlob) {
        // Free some memory for optimal performance
        window.URL.revokeObjectURL(image.src);
      }
    });

    image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;

  });

  // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
  reader.readAsDataURL(file);  
}

// 1.
// Once the user selects all the files to upload
// that will trigger a `change` event on the `#browse` input
elBrowse.addEventListener("change", function() {

  // Let's store the FileList Array into a variable:
  // https://developer.mozilla.org/en-US/docs/Web/API/FileList
  var files  = this.files;
  // Let's create an empty `errors` String to collect eventual errors into:
  var errors = "";

  if (!files) {
    errors += "File upload not supported by your browser.";
  }

  // Check for `files` (FileList) support and if contains at least one file:
  if (files && files[0]) {

    // Iterate over every File object in the FileList array
    for(var i=0; i<files.length; i++) {

      // Let's refer to the current File as a `file` variable
      // https://developer.mozilla.org/en-US/docs/Web/API/File
      var file = files[i];

      // Test the `file.name` for a valid image extension:
      // (pipe `|` delimit more image extensions)
      // The regex can also be expressed like: /\.(png|jpe?g|gif)$/i
      if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
        // SUCCESS! It's an image!
        // Send our image `file` to our `readImage` function!
        readImage( file ); 
      } else {
        errors += file.name +" Unsupported Image extension\n";  
      }
    }
  }

  // Notify the user for any errors (i.e: try uploading a .txt file)
  if (errors) {
    alert(errors); 
  }

});

JSFIDDLE

查看更多
零度萤火
6楼-- · 2018-12-31 07:16

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.

查看更多
爱死公子算了
7楼-- · 2018-12-31 07:23

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

查看更多
登录 后发表回答