6

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.

1
  • 3
    That is how you Base64 encode data. The problem must be somewhere else. Commented Sep 14, 2016 at 9:28

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your second parameter is 75, it should be 0.7

let imageData = UIImageJPEGRepresentation(globalImage!, 0.7)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.