ios 如何从 Swift 中的 Base64 编码字符串创建图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28709964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I create an image from a Base64-encoded string in Swift?
提问by Michael Voccola
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 编码的图像作为字符串回显。如何在 Swift 项目中解码和显示此编码图像?
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.
具体来说,我想取一张图片,该图片已经由Web服务提供为Base64格式的字符串,并了解如何在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?
到目前为止,我发现的文章描述了不推荐使用的技术,或者是用我不熟悉的 Objective-C 编写的。如何接收 Base64 编码的字符串并将其转换为 UIImage?
回答by Stefan Arentz
Turn your base64 encoded string into an NSData
instance by doing something like this:
NSData
通过执行以下操作将您的 base64 编码字符串转换为实例:
let encodedImageData = ... get string from your web service ...
let imageData = NSData(base64EncodedString: encodedImageData options: .allZeros)
Then turn the imageData into a UIImage:
然后把imageData变成UIImage:
let image = UIImage(data: imageData)
You can then set the image on a UIImageView
for example:
然后,您可以将图像设置在UIImageView
例如:
imageView.image = image
回答by Raptor
To decode Base64 encoded string to image, you can use the following code in Swift:
要将 Base64 编码的字符串解码为图像,您可以在 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.
更好的是,您可以在分配给图像视图之前检查是否decodedimage
是nil
。