上传图片前获取其尺寸

上传图片前有时需要判断用户提交的图片是否符合一定的尺寸规格,通常的解决办法是先将图片传送到后台,然后再判断,但这样增加了开支,提高了消耗,安全性也不高。因此最好能够在前端就能进行简单的判断,但是由于浏览器兼容性的问题,往往做起来非常麻烦。ie还好,因为本身就可以通过new Image()的方式直接获得尺寸,而chrome等高级点浏览器就不那么直接了,不过好在有了html5的支持,里面提供了FileReader()这个接口,可以方便地读取文件内容和信息。

 1 $('#fileInput').change(function(e) {
 2         if(typeof FileReader != 'undefined') {
 3             readImage(this, showImage);
 4         } else {
 5             showImage(this.value);
 6         }
 7     });
 8     function showImage(src) {
 9         var img = new Image();
10         img.onload = function() {
11             document.body.appendChild(img);
12             alert([this.width, this.height].join(','));
13         }
14         img.src = src;
15     }
16     function readImage(that, callback){
17         var file = that.files[0];
18 19         if(!/image\/\w+/.test(file.type)){
20             alert("请确保文件为图像类型");
21             return false;
22         }
23         var reader = new FileReader();
24         reader.readAsDataURL(file);
25         reader.onload = function(e){
26             if(callback) callback.call(this, this.result);
27         }
28     }

 

posted @ 2012-12-04 18:23  bilipan  阅读(357)  评论(0编辑  收藏  举报