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

前端 未结 9 1432
一向
一向 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条回答
  • 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()
    
    0 讨论(0)
  • 2020-12-02 07:49

    Use imageWithData: method, which gets translated to Swift as UIImage(data:)

    let image : UIImage = UIImage(data: imageData)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-02 07:53

    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)
    
    0 讨论(0)
  • 2020-12-02 07:55

    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()
    
    0 讨论(0)
  • 2020-12-02 08:00

    Swift 5

    let the image you create as UIImage be image

    image.pngData() as NSData? 
    
    0 讨论(0)
提交回复
热议问题