+ (CGSize)downloadJPGImageSizeWithRequest:(NSMutableURLRequest*)request {
[request setValue:@"bytes=0-209" forHTTPHeaderField:@"Range"];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if ([data length] <= 0x58) {
return CGSizeZero;
}
if ([data length] < 210) {// 肯定只有一个 DQT 字段
short w1 = 0, w2 = 0;
[data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
[data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
short w = (w1 << 8) + w2;
short h1 = 0, h2 = 0;
[data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
[data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
short h = (h1 << 8) + h2;
return CGSizeMake(w, h);
} else {
short word = 0x0;
[data getBytes:&word range:NSMakeRange(0x15, 0x1)];
if (word == 0xdb) {
[data getBytes:&word range:NSMakeRange(0x5a, 0x1)];
if (word == 0xdb) {// 两个 DQT 字段
short w1 = 0, w2 = 0;
[data getBytes:&w1 range:NSMakeRange(0xa5, 0x1)];
[data getBytes:&w2 range:NSMakeRange(0xa6, 0x1)];
short w = (w1 << 8) + w2;
short h1 = 0, h2 = 0;
[data getBytes:&h1 range:NSMakeRange(0xa3, 0x1)];
[data getBytes:&h2 range:NSMakeRange(0xa4, 0x1)];
short h = (h1 << 8) + h2;
return CGSizeMake(w, h);
} else {// 一个 DQT 字段
short w1 = 0, w2 = 0;
[data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
[data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
short w = (w1 << 8) + w2;
short h1 = 0, h2 = 0;
[data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
[data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
short h = (h1 << 8) + h2;
return CGSizeMake(w, h);
}
} else {
return CGSizeZero;
}
}
}
1
sutra 2016-04-28 18:20:05 +08:00
方法 1. 在获得图片 URL 时的 API 请求中就告知客户端图片的 meta 信息。
方法 2. 使用 HTTP Head 请求: $ curl -I 'https://www.baidu.com/img/bd_logo1.png' HTTP/1.1 200 OK Server: bfe/1.0.8.14 Date: Thu, 28 Apr 2016 10:21:46 GMT Content-Type: image/png Content-Length: 7877 Connection: keep-alive P3P: CP=" OTI DSP COR IVA OUR IND COM " Set-Cookie: BAIDUID=0D422F47D99BEF3218B73FC146CF8608:FG=1; expires=Fri, 28-Apr-17 10:21:46 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1 Last-Modified: Wed, 03 Sep 2014 10:00:27 GMT ETag: "1ec5-502264e2ae4c0" Accept-Ranges: bytes Cache-Control: max-age=315360000 Expires: Sun, 26 Apr 2026 10:21:46 GMT |
2
CDuXZMAPgHp1q9ew 2016-04-28 18:36:40 +08:00
lz 要的大小是图片宽高 不是文件大小
可以通过只读 jpg 的前几个字节来确认大小 有个现成的库 不记得了.... |
3
xiaket 2016-04-28 18:42:50 +08:00
嗯, 思路很简单, HTTP 加一个 range 的 header, 读前几个字节, 解出相关信息就行.
|
7
CDuXZMAPgHp1q9ew 2016-04-29 09:49:11 +08:00
|
8
CDuXZMAPgHp1q9ew 2016-04-29 09:50:29 +08:00 1
|
10
kkzxak47 2016-04-29 13:43:15 +08:00
平时也经常处理图片,发现很多 jpg 扩展名的文件实际上存的是 png/gif ……
所以要想最靠谱还是自己读文件头,判定真实文件格式,再根据不同格式去找高宽怎么存的 |