Created
March 5, 2017 23:55
-
-
Save benbahrenburg/e529c28de0260733054516e6eee0edf5 to your computer and use it in GitHub Desktop.
Using ImageIO and Swift to convert a UIImage to Data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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