Using ImageIO and Swift to convert a UIImage to Data
This file contains 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