Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage to String and String to UIImage in Swift

I add name of the user and photo user to UserDefaults array then send this array to my site + insert this array in another ViewController

Code to save:

 let imageSaveData = UIImageJPEGRepresentation(self.profileUserPhotoImage.image!, 1.0) as NSData?    
 let base64String = imageSaveData?.base64EncodedString()
    let userNameAdnPhoto = ["name": self.userNameLabel.text, "image": base64String] as? [String: String]
    var userArrayToUDef = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]]

In another ViewController I don't know how to get from UserDefaults.standard.array(forKey: "userInfo") image to UIImageView in ViewController

like image 541
Nazar Avatar asked Apr 29 '18 09:04

Nazar


Video Answer


3 Answers

String image convert in to UIImage

String to UIImage

yourString.toImage() // it will convert String  to UIImage

extension String {
    func toImage() -> UIImage? {
        if let data = Data(base64Encoded: self, options: .ignoreUnknownCharacters){
            return UIImage(data: data)
        }
        return nil
    }
}

Convert UIImage to string then this is used

UIImage to String

yourImage.toPngString() // it will convert UIImage to string

extension UIImage {
    func toPngString() -> String? {
        let data = self.pngData()
        return data?.base64EncodedString(options: .endLineWithLineFeed)
    }
  
    func toJpegString(compressionQuality cq: CGFloat) -> String? {
        let data = self.jpegData(compressionQuality: cq)
        return data?.base64EncodedString(options: .endLineWithLineFeed)
    }
}
like image 147
AshvinGudaliya Avatar answered Oct 23 '22 00:10

AshvinGudaliya


This function is just for string to UIImage.

  extension String {

        func stringToImage(_ handler: @escaping ((UIImage?)->())) {
            if let url = URL(string: self) {
                URLSession.shared.dataTask(with: url) { (data, response, error) in
                    if let data = data {
                        let image = UIImage(data: data)
                        handler(image)
                    }
                }.resume()
            }
        }
    }

use this function as,

            yourString.stringToImage {(image) in
              self.yourPhoto.image = image
            }

like image 45
Ronak Patel Avatar answered Oct 22 '22 23:10

Ronak Patel


Nowadays, "UIImagePNGRepresentation" method is updated to "pngData()" method.

If you want to convert UIImage to String, you can use the following lines:

extension UIImage {
    func toString() -> String? {

        let pngData = self.pngData()

        //let jpegData = self.jpegData(compressionQuality: 0.75)

        return pngData?.base64EncodedString(options: .lineLength64Characters)
    }
}
like image 40
AngelesVP Avatar answered Oct 23 '22 01:10

AngelesVP