Jacob Platin Jacob Platin - 3 months ago 16
iOS Question

Base64 conversion with UIImage: NSData is not nil, but UIImage is nil

I am currently converting a user-picked

UIImage
to a base64 string using the below method, but when I go to convert that back into an image using the below method, I can get the
NSData
, but I can't convert that into a
UIImage
. Any thoughts? I have already tried using both PNG and JPEG methods for the
UIImage
, and neither worked if that adds any detail.

Thanks,

Jacob

Encoding Code:

var base64 = UIImagePNGRepresentation(self.profileView.image!))!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)


Decoding Code:

let decodedData = NSData(base64EncodedString: String(user?.photoURL), options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
let decodedimage = UIImage(data: decodedData!) //this decoded image is nil

Answer

You can try with code:

let image : UIImage = UIImage(named:"your_image")!
let imageData:NSData = UIImagePNGRepresentation(image)!

Encoding:

let base64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)

Decoding

let dataDecoded:NSData = NSData(base64EncodedString: base64, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)!

Here is the code to convert NSData to UIImage

let image: UIImage = UIImage(data:dataDecoded,scale:1.0)

I hope this helps.

Comments