在Swift4中出现错误的Base64图像

时间:2018-03-19 13:19:17

标签: ios swift encoding base64

我想为特定图像生成Base64字符串。 因为我已经写下了代码

let imageData = UIImagePNGRepresentation(imgProfile.image!)!
var imageStr = imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)

我将this输出字符串作为Base64,未解码(即错误)。

但是当我从here生成Base64时,我得到this输出字符串,该字符串已成功解码并返回图像(即正确)

请帮我找到问题。
提前致谢

我已经访问了以下主题 1. https://stackoverflow.com/a/47610733/3110026
2. https://stackoverflow.com/a/46309421/3110026

3 个答案:

答案 0 :(得分:0)

尝试下面的UIImage扩展程序:

extension UIImage {



    /// Encoded Base64 String of the image
    var base64: String? {
        guard let imageData = UIImageJPEGRepresentation(self, 1.0) as NSData? else {
            print("Error occured while encoding image to base64. In \(self), \(#function)")
            return nil
        }
        return imageData.base64EncodedString()
    }


}

答案 1 :(得分:0)

字符串已正确编码。您使用所传递的选项在每64个字符后添加CRLF(\n\r)。

最简单的解决方案是传递无选项

let imageData = UIImagePNGRepresentation(imgProfile.image!)!
let imageStr = imageData.base64EncodedString()

或使用选项ignoreUnknownCharacters

解码数据
let imageData = UIImagePNGRepresentation(imgProfile.image!)!
let imageStr = imageData.base64EncodedString(options: .lineLength64Characters)
...
if let data = Data(base64Encoded: imageStr, options: .ignoreUnknownCharacters) { ...

答案 2 :(得分:0)

另外, 我遇到了同样的问题,但对我来说,不是\ r \ n问题,当我从服务器获取base64字符串时,某些字符之间存在空格,并将其与正确的Base64字符串进行比较后,我发现我必须在空格中添加“ +”号。当我这样做的时候... “ yourBase64String”可以包含\ r \ n。

if let cleanImageString =  yourBase64String.replacingOccurrences(of: " ", with: "+") {
        if let data = Data(base64Encoded: cleanImageString, options: .ignoreUnknownCharacters) {
            yourImageView.image = UIImage(data: data)
        }
    }
相关问题