I\'m trying to save a UIImage
to NSData
and then read the NSData
back to a new UIImage
in Swift. To convert the UII
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()
Use imageWithData: method, which gets translated to Swift as UIImage(data:)
let image : UIImage = UIImage(data: imageData)
To save as data:
From StoryBoard, if you want to save "image" data on the imageView of MainStoryBoard, following codes will work.
let image = UIImagePNGRepresentation(imageView.image!) as NSData?
To load "image" to imageView: Look at exclamation point "!", "?" closely whether that is quite same as this one.
imageView.image = UIImage(data: image as! Data)
"NSData" type is converted into "Data" type automatically during this process.
Image to Data:-
if let img = UIImage(named: "xxx.png") {
let pngdata = img.pngData()
}
if let img = UIImage(named: "xxx.jpeg") {
let jpegdata = img.jpegData(compressionQuality: 1)
}
Data to Image:-
let image = UIImage(data: pngData)
Now in Swift 4.2 you can use pngData()
new instance method of UIImage
to get the data from the image
let profileImage = UIImage(named:"profile")!
let imageData = profileImage.pngData()
Swift 5
let the image you create as UIImage be image
image.pngData() as NSData?