Skip to content

Instantly share code, notes, and snippets.

@d4rkd3v1l
Last active November 29, 2017 14:33
Show Gist options
  • Save d4rkd3v1l/6824c0dfb10838b56aa08d8e1aa374bb to your computer and use it in GitHub Desktop.
Save d4rkd3v1l/6824c0dfb10838b56aa08d8e1aa374bb to your computer and use it in GitHub Desktop.
iOS: How to retrieve image dimensions without loading CGImage into memory
// This method requires ImageIO.framework
#import <ImageIO/ImageIO.h>
- (CGSize)sizeOfImageAtURL:(NSURL *)imageURL
{
// With CGImageSource we avoid loading the whole image into memory
CGSize imageSize = CGSizeZero;
CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)imageURL, NULL);
if (source) {
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCGImageSourceShouldCache];
CFDictionaryRef properties = (NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, 0, (CFDictionaryRef)options);
if (properties) {
NSNumber *width = [(NSDictionary *)properties objectForKey:(NSString *)kCGImagePropertyPixelWidth];
NSNumber *height = [(NSDictionary *)properties objectForKey:(NSString *)kCGImagePropertyPixelHeight];
if ((width != nil) && (height != nil))
imageSize = CGSizeMake(width.floatValue, height.floatValue);
CFRelease(properties);
}
CFRelease(source);
}
return imageSize;
}
func getSizeOfImageAtURL(_ url: URL) -> CGSize? {
let options: [NSString: NSObject] = [kCGImageSourceShouldCache: false as NSObject]
guard
let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil),
let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, options as CFDictionary) as? [String: Any],
let width = properties[kCGImagePropertyPixelWidth as String] as? NSNumber,
let height = properties[kCGImagePropertyPixelHeight as String] as? NSNumber else {
return nil
}
return CGSize(width: CGFloat(truncating: width), height: CGFloat(truncating: height))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment