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
?
Now in Swift 4.2 you can use
pngData()
new instance method ofUIImage
to get the data from the imageUse
imageWithData:
method, which gets translated to Swift asUIImage(data:)
UIImage(data:imageData,scale:1.0)
presuming the image's scale is 1.Image to Data:-
Data to Image:-
let image = UIImage(data: pngData)
Thanks. Helped me a lot. Converted to Swift 3 and worked
To save:
let data = UIImagePNGRepresentation(image)
To load:
let image = UIImage(data: data)
For safe execution of code, use
if-let
block withData
to prevent app crash & , as functionUIImagePNGRepresentation
returns an optional value.Generic image operations (like png & jpg both):
By using extension: