iOS-获取图像尺寸

在执行下述方法之前,我们要先导入头文件 #import

/**
 *  根据图片url获取图片尺寸 
 */
+ (CGSize)getImageSizeWithURL:(id)URL{    
    NSURL * url = nil;    
    if ([URL isKindOfClass:[NSURL class]]) {        
        url = URL;    
    }    
    if ([URL isKindOfClass:[NSString class]]) {        
        url = [NSURL URLWithString:URL];    
    }   
     if (!URL) {        
        return CGSizeZero;  // url不正确返回CGSizeZero    
    }    
    CGImageSourceRef imageSourceRef = CGImageSourceCreateWithURL((CFURLRef)url, NULL);    
    CGFloat width = 0, height = 0;       
    if (imageSourceRef) {        
        CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSourceRef, 0, NULL);               
        if (imageProperties != NULL) {                       
            CFNumberRef widthNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);          
            if (widthNumberRef != NULL) {                
                CFNumberGetValue(widthNumberRef, kCFNumberFloat64Type, &width);            
            }                       
            CFNumberRef heightNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
            if (heightNumberRef != NULL) {
                CFNumberGetValue(heightNumberRef, kCFNumberFloat64Type, &height);
            }
            CFRelease(imageProperties);
        }
        CFRelease(imageSourceRef);    
    }    
    return CGSizeMake(width, height);
}

你可能感兴趣的:(iOS-获取图像尺寸)