Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 encoding with Swift 3

How do you encode an image to base64 in Swift 3.0?

I tried to do it this way:

let imageData = UIImageJPEGRepresentation(globalImage!, 75)
let string64 = imageData!.base64EncodedString()

where globalImage is my image. I successfully sent the data to my web server but when I try to load the image it's not in a form that my computer can recognize.

like image 455
fllawlezz Avatar asked Nov 09 '22 09:11

fllawlezz


1 Answers

Here are the encoding and decoding methods.

func encodeImageToBase64(image : UIImage) -> String{

   let imageData : Data = UIImagePNGRepresentation(image)! as Data
   let strBase64 = imageData.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0))
   return strBase64
}

func decodeBase64ToImage(base64 : String) -> UIImage{

    let dataDecoded : NSData = NSData(base64Encoded: base64, options: NSData.Base64DecodingOptions(rawValue: 0))!
    let decodedimage : UIImage = UIImage(data: dataDecoded as Data)!
    return decodedimage
}
like image 128
Usman Javed Avatar answered Nov 14 '22 23:11

Usman Javed