快速将UIImage转换为base64字符串 [英] Convert UIImage to base64 string in swift
问题描述
我正在尝试将UIImage转换为base64字符串,目的是将其上传到后端服务器.
I'm trying to convert a UIImage to a base64 string with the goal of uploading it to a back-end server.
但是,我在本文中找到的转换代码(应该是Apple自己的实现)会生成无效的字符串:
However, the conversion code I found in this article (which should be Apple's own implementation) generates an invalid string:
上传后,我得到了这张图片:
After upload, I get this image:
[从iOS转换的base64解码的故障图像 1
[Failty image that is decoded from iOS converted base64 1
代替此:
[通过在线base64转换工具解码的正确图像 2
[Correct image decoded from an online base64 conversion tool2
我使用Postman测试了上传结果,后端正确处理了有效的base64图像,因此我将错误缩小到了base64转换本身.这是我的代码:
I tested the upload results using Postman and the back-end handles a valid base64 image correctly, so I narrowed the bug down to the base64 conversion itself. Here's my code:
public extension UIImage
{
func base64Encode() -> String?
{
guard let imageData = UIImagePNGRepresentation(self) else
{
return nil
}
let base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
let fullBase64String = "data:image/png;base64,\(base64String))"
return fullBase64String
}
}
您知道在将iOS设备上的base64输出上传到服务器之前如何解决该问题吗?
Any idea how I could fix my base64 output on my iOS device before I upload it to the server?
推荐答案
执行以下操作:
用于编码:
data.base64EncodedStringWithOptions([])
用于解码:
let url = URL(string: String(format:"data:application/octet-stream;base64,%@",base64String))
do {
let data = try Data(contentsOf: url!)
}catch {
}
这篇关于快速将UIImage转换为base64字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!