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?

bzatrok
  • 35
  • 1
  • 1
  • 5
  • That looks absolutely correct to me, what makes you think it's the conversion? Have you checked the conversion algorithm server side? – Jacob King Nov 03 '16 at 07:51
  • 1
    Try `base64EncodedStringWithOptions([])`. You might also have to replace "+", "/" and "=", compare http://stackoverflow.com/a/39376534/1187415. – Martin R Nov 03 '16 at 08:19

2 Answers2

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 {

}
Bhavuk Jain
  • 2,167
  • 1
  • 15
  • 23
  • 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`. – rmaddy Sep 04 '17 at 17:36
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.

KomalBadhe
  • 29
  • 1