Decode base64_encode Image from JSON in Swift

2020-01-29 17:18发布

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']);

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

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

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?

1条回答
▲ chillily
2楼-- · 2020-01-29 18:08

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)
}
查看更多
登录 后发表回答