Grimxn
Grimxn

Reputation: 22487

Core Graphics alternative to UIImage/NSImage file representations

I have a CGImage that I have manipulated, and I wish to write it to file (or, rather, end up with an NSData representation suitable for writing to file). I know "how" to do this in both OSX & iOS, but only using the platform dependent calls, not the Core Graphics calls. I cannot find any documentation on how to do this in a platform independent way. Here's what I have:

func newImageData() -> NSData? {
    var newImageRef: CGImage
    // ...
    // Create & manipulate newImageRef
    // ...
    #if os(iOS)
        let newImage = UIImage(CGImage: newImageRef, scale: 1, orientation: 0)
        return UIImagePNGRepresentation(newImage)
    #elseif os(OSX)
        let newImage = NSImage(CGImage: newImageRef, size: NSSize(width: width, height: height))
        return newImage.TIFFRepresentation
    #endif
}

Just to be clear - the code above works fine, I am just frustrated that having done everything else in CG, I have to step out of it to get the file representation.

Finally, I don't care that one platform returns a PNG and the other a TIFF - in actual fact this is creating a tile for MKTileOverlay, so either will do...

Upvotes: 1

Views: 698

Answers (2)

Grimxn
Grimxn

Reputation: 22487

Many thanks to @Matt for pointing me in the correct direction - ImageIO framework.

What I needed was this:

let dataOut = CFDataCreateMutable(nil, CFIndex(byteCount))
if let iDest = CGImageDestinationCreateWithData(dataOut, kUTTypePNG, 1, nil) {            
    let options: [NSObject: AnyObject] = [
                kCGImagePropertyOrientation : 1, // Top left
                kCGImagePropertyHasAlpha : true,
                kCGImageDestinationLossyCompressionQuality : 1.0
            ]

    CGImageDestinationAddImage(iDest, newImageRef, options)
    CGImageDestinationFinalize(iDest)
    return dataOut
} else {
    print("Failed to create image destination")
    return nil
}

Upvotes: 3

matt
matt

Reputation: 535306

You are looking for the ImageIO framework, which is the same for both platforms (and, incidentally, is a much better way to save an image to a file than what you are doing now).

Upvotes: 3

Related Questions