iosswiftuiimagebase64uiimagepngrepresentation

Convert UIImage to base64 string in swift


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?


Solution

  • 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 {
    
    }