Convert a UIImage to and from Base64
suggest changeUIImagePNGRepresentation returns nil when the image has no PNG representation. The force-unwraps below crash in that case, and when the Base64 string is not valid image data.
Encoding
//convert the image to NSData first
let imageData:NSData = UIImagePNGRepresentation(image)!
// convert the NSData to base64 encoding
let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
Decoding
let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!
let decodedimage:UIImage = UIImage(data: dataDecoded)!
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents