開發(fā)中經(jīng)常遇到根據(jù)圖片大小動(dòng)態(tài)設(shè)置Cell或者ImageView的寬高的需求使兔,通過圖片的網(wǎng)絡(luò)地址直接獲取圖片的大小就可以實(shí)現(xiàn)這個(gè)需求
Swift代碼:
let imageSource = CGImageSourceCreateWithURL(URL(string: imageURL)! as CFURL, nil)
if let result = CGImageSourceCopyPropertiesAtIndex(imageSource!, 0, nil) as? Dictionary<String, Any> {
print("??\(result)")
if let width = result["PixelWidth"] as? CGFloat, let height = result["PixelHeight"] as? CGFloat {
print("??width:\(width),height:\(height)")
}
}
輸出結(jié)果:
??["PixelHeight": 1152, "{JFIF}": {
DensityUnit = 0;
JFIFVersion = (
1,
0,
1
);
XDensity = 1;
YDensity = 1;
}, "Depth": 8, "ColorModel": RGB, "PixelWidth": 1728]
??width:1728.0,height:1152.0
Objective-C代碼:
#import <ImageIO/ImageIO.h>
NSMutableString *imageURL = [NSMutableString stringWithFormat:@"http://www.myimageurl.com/image.png"];
CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)[NSURL URLWithString:imageURL], NULL);
NSDictionary* imageHeader = (__bridge NSDictionary*) CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
NSLog(@"Image header %@",imageHeader);
CGFloat pixelHeight = [[imageHeader objectForKey:@"PixelHeight"] floatValue];
CGFloat pixelWidth = [[imageHeader objectForKey:@"PixelWidth"] floatValue];
CGSize size = CGSizeMake(pixelWidth, pixelHeight);
參考文章:
iOS獲取網(wǎng)絡(luò)圖片的大小