Convert UIImage to base64 string in swift

11,599

Solution 1

Do it something like this:

For Encoding:

data.base64EncodedStringWithOptions([])

For decoding:

let url = URL(string: String(format:"data:application/octet-stream;base64,%@",base64String))
do {
    let data =  try Data(contentsOf: url!)
}catch {

}

Solution 2

for Swift 4, Do something like this,

For Encoding -

let imgObj = UIImage(named: "photo")    
let imageData = UIImagePNGRepresentation(imgObj!)! as NSData
let base64 = imageData.base64EncodedData(options: .lineLength64Characters)

datatype of base64 variable is Data.

Share:
11,599
bzatrok
Author by

bzatrok

Updated on June 14, 2022

Comments

  • bzatrok
    bzatrok almost 2 years

    I'm trying to convert a UIImage to a base64 string with the goal of uploading it to a back-end server.

    However, the conversion code I found in this article (which should be Apple's own implementation) generates an invalid string:

    Convert between UIImage and Base64 string

    After upload, I get this image:

    [Failty image that is decoded from iOS converted base64 1

    Instead of this:

    [Correct image decoded from an online base64 conversion tool2

    I tested the upload results using Postman and the back-end handles a valid base64 image correctly, so I narrowed the bug down to the base64 conversion itself. Here's my code:

    public extension UIImage
    {
         func base64Encode() -> String?
        {
            guard let imageData = UIImagePNGRepresentation(self) else
            {
                return nil
            }
    
            let base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
            let fullBase64String = "data:image/png;base64,\(base64String))"
    
            return fullBase64String
        }
    }
    

    Any idea how I could fix my base64 output on my iOS device before I upload it to the server?

  • rmaddy
    rmaddy over 6 years
    If you use the Data base64EncodedString(options:) method to encode the Data to a String, then use the Data init?(base64Encoded:, options:) initializer to convert the string back into Data.