2

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?

2
  • That looks absolutely correct to me, what makes you think it's the conversion? Have you checked the conversion algorithm server side? Commented Nov 3, 2016 at 7:51
  • 1
    Try base64EncodedStringWithOptions([]). You might also have to replace "+", "/" and "=", compare stackoverflow.com/a/39376534/1187415. Commented Nov 3, 2016 at 8:19

2 Answers 2

4

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 {

}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.