Convert UIImage to NSData and convert back to UIImage in Swift?

pete picture pete · Aug 30, 2015 · Viewed 152.1k times · Source

I'm trying to save a UIImage to NSData and then read the NSData back to a new UIImage in Swift. To convert the UIImage to NSData I'm using the following code:

let imageData: NSData = UIImagePNGRepresentation(myImage)

How do I convert imageData (i.e., NSData) back to a new UIImage?

Answer

algal picture algal · Aug 30, 2015

UIImage(data:imageData,scale:1.0) presuming the image's scale is 1.

In swift 4.2, use below code for get Data().

image.pngData()