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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With