Swift 获取网络图片大小

开发中经常遇到根据图片大小动态设置Cell或者ImageView的宽高的需求,通过图片的网络地址直接获取图片的大小就可以实现这个需求
Swift代码:

let imageSource = CGImageSourceCreateWithURL(URL(string: imageURL)! as CFURL, nil)
if let result = CGImageSourceCopyPropertiesAtIndex(imageSource!, 0, nil) as? Dictionary {
    print("\(result)")
    if let width = result["PixelWidth"] as? CGFloat, let height = result["PixelHeight"] as? CGFloat {
        print("width:\(width),height:\(height)")
    }
}

输出结果:

["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 

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获取网络图片的大小

你可能感兴趣的:(Swift 获取网络图片大小)