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

前端 未结 9 1506
一向
一向 2020-12-02 07:33

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

9条回答
  •  清歌不尽
    2020-12-02 07:51

    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.

提交回复
热议问题