如何在 Swift 中从 Base64 编码的字符串创建图像? [英] How do I create an image from a Base64-encoded string in Swift?

查看:16
本文介绍了如何在 Swift 中从 Base64 编码的字符串创建图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 编码的字符串创建图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆