fllawlezz
fllawlezz

Reputation: 61

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.

Upvotes: 6

Views: 5254

Answers (2)

Usman Javed
Usman Javed

Reputation: 2455

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
}

Upvotes: 1

ZHENGYING
ZHENGYING

Reputation: 11

Your second parameter is 75, it should be 0.7

let imageData = UIImageJPEGRepresentation(globalImage!, 0.7)

Upvotes: 0

Related Questions