在Swift中解码来自JSON的base64_encode图像

时间:2016-04-25 02:13:38

标签: json swift decode

我有一个包含一些图像的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)
            }

        }

如何解码图像以便我可以显示它?

1 个答案:

答案 0 :(得分:4)

您必须将字典值从AnyObject转换为String。您还必须使用.IgnoreUnknownCharacters选项解码字符串数据。试试这个

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

Swift 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)
}