Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an image from a Base64-encoded string in Swift? [duplicate]

A web service echoes a Base64 encoded image as a string. How can one decode and display this encoded image in a Swift project?

Specifically, I would like to take an image, which is already provided by the web service as a string in Base64 format, and understand how to display it in a UIImageView.

The articles I have found thus far describe deprecated techniques or are written in Objective-C, which I am not familiar with. How do you take in a Base64-encoded string and convert it to a UIImage?

like image 988
Michael Voccola Avatar asked Feb 25 '15 02:02

Michael Voccola


People also ask

Does Base64 encoding reduce image quality?

With the introduction of multiplexing that arrived with HTTP/2, web browsers have become incredibly efficient in delivering hundreds of files through a single connection. This works around most limits that the Base64 encoding solved and in fact means Base64 now does more bad than good.

How does Base64 encoding work for images?

To display that base64 representation in a browser: Browser takes the image/png part and knows that the data following it will be the bytes of a png image. It then sees base64, and knows that the next blob will need to be base64 decoded, before it can then be decoded by its png decoder.


2 Answers

Turn your base64 encoded string into an NSData instance by doing something like this:

let encodedImageData = ... get string from your web service ...
let imageData = NSData(base64EncodedString: encodedImageData options: .allZeros)

Then turn the imageData into a UIImage:

let image = UIImage(data: imageData)

You can then set the image on a UIImageView for example:

imageView.image = image
like image 188
Stefan Arentz Avatar answered Oct 20 '22 14:10

Stefan Arentz


To decode Base64 encoded string to image, you can use the following code in Swift:

let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.fromRaw(0)!)
var decodedimage = UIImage(data: decodedData)
println(decodedimage)
yourImageView.image = decodedimage as UIImage

Even better, you can check if decodedimage is nil or not before assigning to image view.

like image 25
Raptor Avatar answered Oct 20 '22 16:10

Raptor