Episode #181

CGImageSource

16 minutes
Published on August 6, 2015

This video is only available to subscribers. Get access to this video and 572 others.

In this episode we take a look at CGImageSource from the ImageIO framework. Using CGImageSource we can perform operations like resize without loading the entire image into memory. In addition, we can extract image metadata like f-stop, aperture, ISO, and camera/lens information.

Episode Links

Resizing with CGImageSource

Working with CGImageSource requires you to import ImageIO ad the top of the file. For the UTI definitions, import MobileCoreServices.

let url = NSURL(fileURLWithPath: path)
if let imageSource = CGImageSourceCreateWithURL(url, nil) {

    let options = [
        kCGImageSourceCreateThumbnailFromImageIfAbsent as String : kCFBooleanTrue,
        kCGImageSourceCreateThumbnailWithTransform as String : kCFBooleanTrue,
        kCGImageSourceThumbnailMaxPixelSize as String : maxDimension
    ] as NSDictionary
    let resized = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options)
    let targetURL = NSURL(fileURLWithPath: resizedImagePath)
    if let destination =  CGImageDestinationCreateWithURL(targetURL, kUTTypeJPEG, 1, nil) {
        CGImageDestinationAddImage(destination, resized, nil)

        if CGImageDestinationFinalize(destination) {
            println("Resized to \(resizedImagePath)")
        }
    }
}

Extracting Image Metadata

let fileURL = NSURL(fileURLWithPath: path)
if let imageSource = CGImageSourceCreateWithURL(fileURL, nil) {
    let options = [
        (kCGImageSourceShouldCache as! String): kCFBooleanFalse
    ]
    if let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, options) {
        println("Image properties: \(properties)")
        self.imageProperties = properties
        finish()
    }
}

In order to pull the data out of this dictionary, take a look at the keys in the CGImage Property Reference