iOS UIImagePNGRepresentation base64 encode not giving expected output

1.2k views Asked by At

The code

static func encodeImage(image: UIImage) -> String{
    var imageData = UIImagePNGRepresentation(image)
    let base64 = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)
    return base64
}

Does not return the expected output, when the resulting String is decoded in Java or using online tools, the reproduced image is not a valid PNG file

This answer here Base64 encoding in Swift will not decode in Android suggests that the problem is not in the encoding but that the actual PNG is a different format to the one used by Android, iOS seems to use sRGB and Android sBIT

Is there any way to make this work

1

There are 1 answers

6
Ted Huinink On BEST ANSWER

I have had issues as welll with converting images to base64. But that is due to not all signs get escaped correctly. So I made a small function for it that always works for me:

func imageToBase64(imageToDecode: UIImage!) -> String {
    var imageData = UIImageJPEGRepresentation(imageToDecode, 0.8)
    var base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
    base64String = base64String.stringByReplacingOccurrencesOfString("+", withString: "%2B", options: NSStringCompareOptions.LiteralSearch, range: nil)
    base64String = base64String.stringByReplacingOccurrencesOfString("/", withString: "%2F", options: NSStringCompareOptions.LiteralSearch, range: nil)
    return base64String
}