Convert UIImage to base64 string in swift

空扰寡人 提交于 2020-06-12 09:05:45

问题


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?


回答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 {

}



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



来源:https://stackoverflow.com/questions/40396110/convert-uiimage-to-base64-string-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!