Skip to content

Instantly share code, notes, and snippets.

@benbahrenburg
Created March 5, 2017 23:55
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benbahrenburg/e529c28de0260733054516e6eee0edf5 to your computer and use it in GitHub Desktop.
Save benbahrenburg/e529c28de0260733054516e6eee0edf5 to your computer and use it in GitHub Desktop.
Using ImageIO and Swift to convert a UIImage to Data
func UIImageToDataIO(image: UIImage, compressionRatio: CGFloat, orientation: Int = 1) -> Data? {
return autoreleasepool(invoking: { () -> Data in
let data = NSMutableData()
let options: NSDictionary = [
kCGImagePropertyOrientation: orientation,
kCGImagePropertyHasAlpha: true,
kCGImageDestinationLossyCompressionQuality: compressionRatio
]
let imageDestinationRef = CGImageDestinationCreateWithData(data as CFMutableData, kUTTypeJPEG, 1, nil)!
CGImageDestinationAddImage(imageDestinationRef, image.cgImage!, options)
CGImageDestinationFinalize(imageDestinationRef)
return data as Data
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment