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

一直以来我都以为前端只能读取图片的宽度和高度,以及本地上传图片的大小(通过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

转载于:https://my.oschina.net/u/2324376/blog/416890

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值