一尘不染

在Swift中从JSON解码base64_encode图像

swift

我有一个包含一些图像的mysql数据库。我从php文件接收数据:

php:

    $result[$key]['image'] = based64_encode($resultArray[$key]['image']);

现在有了一个Json文件,我得到的是这样的:

Json:
{"image":"\/9j\/4Q\/+RXhpZgAATU0AKgAAAAgACgEPAAIAAAAGAAAAhgEQAAIAAAAKAAAAjAESAAMAAAABAAYAAAEaAAUAAAABAAAAlgEbAAUAAAABAAAAngEoAAMAAAABAAIAAE...

我有一个迅速的项目,想将图像解码成UIImage,到目前为止,我还不知道如何解码图像。我有以下几点。

Swift:
Alamofire.request(.GET, url).responseJSON { (response) -> Void in

        if let JSON = response.result.value as? [[String : AnyObject]]{
            for json in JSON{
                JSON
                let encodedImage = json["image"]
                let imageData = NSData(base64EncodedString: encodedImage)
            }

        }

如何解码图像以便显示?


阅读 244

收藏
2020-07-07

共1个答案

一尘不染

您必须将字典值从AnyObject强制转换为String。您还必须使用.IgnoreUnknownCharacters选项对字符串数据进行解码。这样尝试

if let encodedImage = json["image"] as? String,
    imageData =  NSData(base64EncodedString: encodedImage, options: .IgnoreUnknownCharacters),
    image = UIImage(data: imageData) {
    print(image.size)
}

雨燕3.0.1•Xcode 8.1

if if let encodedImage = json["image"] as? String, 
    let imageData = Data(base64Encoded: encodedImage, options: .ignoreUnknownCharacters),
    let image = UIImage(data: imageData) {
    print(image.size)
}
2020-07-07