我正在尝试通过 JSON 字符串将图像发送到服务器。问题是服务器没有看到我的 PNG 或 JPG 格式的图像。这是我如何做到这一点的代码: enter image description here
我如何将参数转换为 JSON 字符串 enter image description here
我想要的 - 它将 UIImage 编码为 base64 字符串并发送到服务器。 谢谢!
最佳答案
尝试使用下面的代码并检查是否发生任何错误或图像值为零
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
if let imageData = UIImageJPEGRepresentation(image, 0.5) {
let base64String = imageData.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0))
let dict: [String: Any] = ["data": base64String]
do {
let data = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
if let string = String(data: data, encoding: .utf8) {
socket.write(string)
}
} catch {
print(error.localizedDescription)
}
}
}
关于ios - 将 UIImage 转换为 base64 字符串时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44829057/