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

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

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> 

如果你可以使用jQueryvalidation插件,你可以这样做:

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

该函数作为abload函数传递。

代码取自这里

演示

不知道这是你想要的,但只是一个简单的例子:

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

下面是一个纯粹的JavaScript示例:选取图像文件,显示图像,循环显示图像属性,然后将图像从canvas重新设置为IMG标记,并将重新设置大小的图像types显式设置为jpeg。

如果右键单击顶部图像,在canvas标签中,select“另存文件为”,将默认为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> 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:

jsFiddleselect,显示,获取属性和重新调整图像文件的大小

在jsFiddle中,右键单击作为canvas的顶部图像,将不会像右击IMG标记中的底部图像一样提供相同的保存选项。

所以我开始尝试FileReader API提供的不同的东西,并可以创build一个带有DATA URL的IMG标签。

缺点:它不适用于手机,但在Google Chrome浏览器上运行良好。

 $('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> 

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

这里是一篇关于html 5特性的文章,以及一个涉及到使用ActiveX控件的IE浏览器。 http://jquerybyexample.blogspot.com/2012/03/how-to-check-file-size-before-uploading.html

一个正在工作的jQueryvalidation示例:

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