如何在上传之前预览图像,获取文件大小,图像高度和宽度?

时间:2012-09-24 18:36:09

标签: javascript jquery html dimensions image-size

如何使用jQuery或JavaScript在上传到我的网站之前获取文件大小,图像高度和宽度?

7 个答案:

答案 0 :(得分:169)

HTML5和File API

以下是未注明的工作代码段示例

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>


使用输入和div作为图像预览区域

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

让我们也使用CSS来保持结果图像的合理高度:

#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

答案 1 :(得分:7)

如果你可以使用jQuery验证插件,你可以这样做:

<强> 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);
        }
});

该函数作为ab onload函数传递。

代码取自here

答案 2 :(得分:4)

Demo

不确定它是否是你想要的,只是简单的例子:

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;
});

答案 3 :(得分:2)

这是一个纯JavaScript示例,用于选择图像文件,显示图像文件,循环图像属性,然后将图像从画布重新调整为IMG标记,并将重新调整大小的图像类型显式设置为jpeg。

如果右键单击顶部图像,在canvas标签中,选择“将文件另存为”,则默认为PNG格式。如果右键单击,并将文件另存为下图,则默认为JPEG格式。任何宽度超过400像素的文件宽度减少到400像素,高度与原始文件成比例。

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>

这是一个jsFiddle:

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

在jsFiddle中,右键单击顶部图像(即画布),无法在右键单击IMG标记中的底部图像时提供相同的保存选项。

答案 4 :(得分:1)

所以我开始尝试FileReader API必须提供的不同内容,并可以创建带有DATA URL的IMG标记。

缺点:它不适用于手机,但在谷歌浏览器上运行正常。

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

(见http://jsfiddle.net/eD2Ez/530/的jsfiddle上的这个)
(参见我在http://jsfiddle.net/eD2Ez/添加的原始jsfiddle)

答案 5 :(得分:0)

据我所知,没有一种简单的方法可以做到这一点,因为Javascript / JQuery无法访问本地文件系统。 html 5中有一些新功能允许您检查某些元数据,例如文件大小,但我不确定您是否可以实际获取图像尺寸。

这是我发现的关于html 5功能的一篇文章,以及涉及使用ActiveX控件的IE的解决方法。 http://jquerybyexample.blogspot.com/2012/03/how-to-check-file-size-before-uploading.html

答案 6 :(得分:0)

一个有效的jQuery验证示例:

   $(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));