Decoding base64_encode Image from JSON in Swift

I have a mysql database that contains some images. I get data from php file:

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

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

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

I have my quick project and you want to decode the image in UIImage, until I know 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 an image so that it can be displayed?

+2
source share
1 answer

You need to specify the dictionary value from AnyObject to String. You must also decode your string data using the .IgnoreUnknownCharacters parameter. try it

 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) } 
+3
source

Source: https://habr.com/ru/post/1012883/


All Articles