Q:

Swift: 'Compacting' a cropped CGImage

When cropping a CGImage in Swift 3 (using the .cropping method), the original CGImage is referenced by the cropped version - both according to the documentation, and according to what the Allocations instruments shows me. 
I am placing the cropped CGImage objects on an undo stack, so having the original versions retained 'costs' me about 21mb of memory per undo element. 
Since there is no obvious way to 'compact' a cropped CGImage and have it made independent from the original, I have currently done something similar to the following (without all the force unwrapping):
let croppedImage = original.cropping(to: rect)! 
let data = UIImagePNGRepresentation(UIImage(cgImage: croppedImage))! 
let compactedCroppedImage = UIImage(data: data)!.cgImage! 

This works perfectly, and now each undo snapshot takes up only the amount of memory that it is supposed to. 
My question is: Is there a better / faster way to achieve this? 

A:

Your code involves a PNG compression and decompression.  This can be avoided.  Just create an offscreen bitmap of the target size, draw the original image into it and use it as an image:
UIGraphicsBeginImageContext(rect.size)
let targetRect = CGRect(x: -rect.origin.x, y: -rect.origin.y, width: original.size.width, height: original.size.height)
original.draw(in: targetRect)
let croppedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

Note: The result is slightly different if you don't have integral coordinates.