首页 > 代码库 > iOS - 获取本地图片和网络图片的大小size

iOS - 获取本地图片和网络图片的大小size

 

// 获取图片的size
        CGSize size = [UIImage imageNamed:@"20170609.png"].size;

 获取网络图片的尺寸:

 
// 根据图片url获取图片尺寸
+(CGSize)getImageSizeWithURL:(id)imageURL
{
    NSURL* URL = nil;
    if([imageURL isKindOfClass:[NSURL class]]){
        URL = imageURL;
    }
    if([imageURL isKindOfClass:[NSString class]]){
        URL = [NSURL URLWithString:imageURL];
    }
    if(URL == nil)
        return CGSizeZero;                  // url不正确返回CGSizeZero
     
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
    NSString* pathExtendsion = [URL.pathExtension lowercaseString];
     
    CGSize size = CGSizeZero;
    if([pathExtendsion isEqualToString:@"png"]){
        size =  [self getPNGImageSizeWithRequest:request];
    }
    else if([pathExtendsion isEqual:@"gif"])
    {
        size =  [self getGIFImageSizeWithRequest:request];
    }
    else{
        size = [self getJPGImageSizeWithRequest:request];
    }
    if(CGSizeEqualToSize(CGSizeZero, size))                    // 如果获取文件头信息失败,发送异步请求请求原图
    {
        NSData* data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:URL] returningResponse:nil error:nil];
        UIImage* image = [UIImage imageWithData:data];
        if(image)
        {
            size = image.size;
        }
    }
    return size;
}
//  获取PNG图片的大小
+(CGSize)getPNGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=16-23" forHTTPHeaderField:@"Range"];
    NSData* data = http://www.mamicode.com/[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];"bytes=6-9" forHTTPHeaderField:@"Range"];
    NSData* data = http://www.mamicode.com/[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];"bytes=0-209" forHTTPHeaderField:@"Range"];
    NSData* data = http://www.mamicode.com/[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];>

iOS - 获取本地图片和网络图片的大小size