在Swift中从JSON解码base64_encode图像 [英] Decode base64_encode Image from JSON in Swift

查看:200
本文介绍了在Swift中从JSON解码base64_encode图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a mysql database which contains some images. I receive the data from a php file:

php:

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

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

Now with a Json file, I get something like this:

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

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

I have my swift project and want to decode the image into a UIImage, so far I have no idea how to decode the image. I have the following.

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

        }

如何解码图像以使其显示?

How can I decode the image so that I can display it?

推荐答案

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

You have to cast your dictionary value from AnyObject to String. You have also to decode your string data using .IgnoreUnknownCharacters option. Try like this

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

这篇关于在Swift中从JSON解码base64_encode图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆