问题描述
Web服务将Base64编码的图像作为字符串回显.如何在Swift项目中解码并显示此编码图像?
A web service echoes a Base64 encoded image as a string. How can one decode and display this encoded image in a Swift project?
具体地说,我想获取一个图像,该图像已经由Web服务提供为Base64格式的字符串,并了解如何在UIImageView中显示它.
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.
到目前为止,我发现的文章描述了不推荐使用的技术,或者用我不熟悉的Objective-C编写.如何接收Base64编码的字符串并将其转换为UIImage?
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?
推荐答案
通过以下操作将base64编码的字符串转换为NSData
实例:
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)
然后将imageData转换为UIImage:
Then turn the imageData into a UIImage:
let image = UIImage(data: imageData)
然后您可以将图像设置在UIImageView
上,例如:
You can then set the image on a UIImageView
for example:
imageView.image = image
这篇关于如何在Swift中从Base64编码的字符串创建图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!