ios - 快速解码 base64 字符串出错

标签 ios swift image base64

上下文如下:我写了一个应用程序,它可以从你的库中选择一个图像,然后它将图像转换为 base64 字符串,如下所示:

    let imageData:NSData = UIImageJPEGRepresentation(self.myImageView.image!, 0.1)! as NSData
    let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)

这里的 myImageView 是选择图像时存储图像的地方。然后我将其上传到我的本地 mysql 数据库中,其中我有 MEDIUMTEXT 类型的列。然后我写了一个可以从数据库中获取这个字符串的应用程序,但是当我想解码它并再次使它成为 UIimage 时,我的程序失败了。这是我尝试过的:

    let dataDecoded:NSData = NSData(base64Encoded: tempString64, options: NSData.Base64DecodingOptions(rawValue: 0))!
    let decodedimage:UIImage = UIImage(data: dataDecoded as Data)!

这里的tempString64是我从数据库中得到的字符串(我也检查过它不为空)。如果我运行该应用程序,我会在尝试解包时收到 dataDecoded 为 nil 的错误。我真的不明白为什么它是零,而我的 tempString 确实存在。

谢谢。

更新: 我尝试了很多东西,但它不起作用!这是我现在在 URLSession 中使用的代码的相关部分:

   if data != nil {
            do {
                let imagesJSON =  try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
                let images : NSArray = imagesJSON["images"] as! NSArray
                let temp : NSArray = images[0] as! NSArray
                var tempString64 : String = temp[0] as! String
                // I found a question on this site that said that the string should be of length multiple of 4, the following does that.
                let remainder = tempString64.count % 4
                if remainder > 0 {
                    tempString64 = tempString64.padding(toLength: tempString64.count + 4 - remainder,
                                                  withPad: "=",
                                                  startingAt: 0)
                }
                //check if string is not nil
                print(tempString64)

                let dataDecoded = Data(base64Encoded: tempString64)
                let decodedimage = UIImage(data: dataDecoded!)

               DispatchQueue.main.async {
                    self.myImageView.image = decodedimage
                }

            } catch {
                print(error)
            }
        }

tempString64 的尾部

wBr9KavclvUrxPlNp6ircQ5qNLTDfe/Sr8Vvj L9KqS0BbEM2AKz2rXmt8j736VRNr/ALX6UJEmcv3qnPSpRZ/N979Kn y8fe/SqKiZhNJV1rP/AGv0pPsf 1 lEkJlFhkYpAoQe9aH2Pj736VE1n/t/pTV7DRXjPzVpL0qGCy5yX/StEW2B979KLFrYzpadafxfhU8ltn L9Kktrbbu b07Uraktn/2Q==

tempString64的长度是13752

最佳答案

问题是由 lineLength64Characters 选项引起的。如果指定了此选项,则必须使用选项 ignoreUnknownCharacters

解码数据
let dataDecoded  = Data(base64Encoded: tempString64, options: .ignoreUnknownCharacters)!

但是省略所有选项要容易得多。无论如何,数据库并不关心漂亮的格式。

let strBase64 = imageData.base64EncodedString()

...

let dataDecoded  = Data(base64Encoded: tempString64)!

更新:

去掉填充码,安全得到编码后的字符串。 API 会为您处理填充。

不要在 Swift 中使用 NSArrayNSDictionary,使用原生类型安全类型。而且永远不要使用.mutableContainers,特别是您将值分配给im可变常量。该选项在 Swift 中毫无意义。

 if let data = data {
    do {
        if let imagesJSON =  try JSONSerialization.jsonObject(with: data) as? [String:Any],
           let images = imagesJSON["images"] as? [Any],
           let temp = images.first as? [String],
           let tempString64 = temp.first {

           print(tempString64)

           let dataDecoded = Data(base64Encoded: tempString64)
           let decodedimage = UIImage(data: dataDecoded!)

           DispatchQueue.main.async {
               self.myImageView.image = decodedimage
           }
       }

    } catch {
        print(error)
    }
}

关于ios - 快速解码 base64 字符串出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52025591/

相关文章:

ios - 将 UILabel 高度调整为文本

ios - Swift (iOS) 插件 - 插件错误中未定义方法 - Cordova

image - 为什么 magento 中的 wysiwyg 插件让我断开链接?

c# - 在 WPF 中使用图像和图标

ios - iPad 以编程方式创建一个 UITableViewCell

iphone - 如何在 iOS 中获取个人热点的子网掩码和广播地址

ios - 在内存不足的情况下检索图像

ios - 如何快速将波斯日期转换为公历

ios - Swift 如何修改从手机相机拍摄的图像中的 exif 信息

ios - 无法将类型 'Class<T>' 的值分配给类型 'protocol<UIImagePickerControllerDelegate, UINavigationControllerDelegate>?'