如何从ios中的URL获取图像大小

时间:2016-05-24 08:41:03

标签: objective-c afnetworking sdwebimage

如何从objective-C中的URL获取图像的大小(高度/宽度)?我希望我的容器大小根据图像。我正在使用AFNetworking 3.0. 如果符合我的要求,我可以使用SDWebImage

5 个答案:

答案 0 :(得分:12)

在许多情况下,在实际加载图像之前知道图像的大小是必要的。例如,在稍后在cellForRowAtIndexPath中加载实际图像时,在heightForRowAtIndexPath方法中设置tableView单元格的高度(这是非常频繁的捕获22)。

一种简单的方法是使用Image I / O接口从服务器URL读取图像头:

#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);
NSLog(@"PixelHeight %@",[imageHeader objectForKey:@"PixelHeight"]);

答案 1 :(得分:2)

Swift 4.x
Xcode 12.x

func sizeOfImageAt(url: URL) -> CGSize? {
    // with CGImageSource we avoid loading the whole image into memory
    guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else {
        return nil
    }
    
    let propertiesOptions = [kCGImageSourceShouldCache: false] as CFDictionary
    guard let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, propertiesOptions) as? [CFString: Any] else {
        return nil
    }
    
    if let width = properties[kCGImagePropertyPixelWidth] as? CGFloat,
       let height = properties[kCGImagePropertyPixelHeight] as? CGFloat {
        return CGSize(width: width, height: height)
    } else {
        return nil
    }
}

答案 2 :(得分:1)

你可以这样试试:

NSData *data = [[NSData alloc]initWithContentsOfURL:URL]; 
UIImage *image = [[UIImage alloc]initWithData:data];
CGFloat height = image.size.height;
CGFloat width = image.size.width;

答案 3 :(得分:0)

在iOS中使用名为GCD的异步机制来下载图像而不影响主线程。

P2-[connects_to]-P3

答案 4 :(得分:0)

对于 Swift 4 ,使用此方法:

let imageURL = URL(string: post.imageBigPath)!
let source = CGImageSourceCreateWithURL(imageURL as CFURL,     
let imageHeader = CGImageSourceCopyPropertiesAtIndex(source!, 0, nil)! as NSDictionary;
print("Image header: \(imageHeader)")

标题看起来像:

  

图片标题:{       ColorModel = RGB;       深度= 8;       PixelHeight = 640;       PixelWidth = 640;       “ {Exif}” = {           PixelXDimension = 360;           PixelYDimension = 360;       };       “ {JFIF}” = {           DensityUnit = 0;           JFIFVersion =(               1,               0,               1个           );           XDensity = 72;           YDensity = 72;       };       “ {TIFF}” = {           方向= 0;       }; }

因此您可以从中获取宽度,高度。