您的位置:首页 > Web前端 > JavaScript

WEB端获取远程图片的尺寸和大小

2015-05-19 00:00 531 查看
摘要: 通过image.onload读取长度和宽度,通过ajax请求获取大小

一直以来我都以为前端只能读取图片的宽度和高度,以及本地上传图片的大小(通过FileReader),但不能获取到远程图片的大小。

昨天在搜索时突然意识到,http headers中包含
Content-Length
参数,这不就是大小吗?!然后立马在console输入
$.get(src, function(data, statusText, res){res.getAllResponseHeaders()})
,这不就搞定了嘛!

但是我高兴太早了:expressionless: 把这个放在代码里,愣是不显示
Content-Length


然后继续分析输出,嘿嘿,data不就是图片吗?其长度不就是图片原始大小吗?!

是的,事情就是这个样子的:triumph:代码如下:

var img = new Image();
img.onload = function() { // 先获取长度和宽度(像素)
$.ajax({ // 再获取图片大小(kb)
url: src,
type: 'GET',
complete: function(xhr, statusText) {
console.log(img.width, img.height, xhr.status === 200 ? (xhr.responseText.length/1024).toFixed(2) : 0);
}
});
};
img.src = src;

补:
getResponseHeader()
不能获取
content-length
解读:

The XMLHttpRequest 2 object has a getResponseHeader() method that returns the value of a particular response header. During a CORS request, the getResponseHeader() method can only access simple response headers. Simple response headers are defined as follows:

- Cache-Control
- Content-Language
- Content-Type
- Expires
- Last-Modified
- Pragma

If you want clients to be able to access other headers, you have to use the Access-Control-Expose-Headers header. The value of this header is a comma-delimited list of response headers you want to expose to the client.

补2:如果是通过
input[type="file"]
上传的文件,直接读取
file.size
可获取文件大小。

补3:偶然发现一个不需要
new Image
获取图片尺寸的思路,参考Marijn Haverbeke在Beautiful Javascript中的示例。不过该实现只支持部分PNG图片。

http://my.oschina.net/u/2324376/blog/416890
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息