ios - 将 UIImage 转换为 base64 字符串时失败

标签 ios swift encoding uiimage base64

我正在尝试通过 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/

相关文章:

iOS 64 位兼容性

json - 如何在 Swift 上通过 Mashape 打印 JSON 数据?

swift - 元素与通用类型 <T>

java - MySql 数据库中的数据不正确

java - 如何避免native2ascii UTF编码BOM头?

python - 有没有办法将 unicode 编码成人类可读的 base64 变体(在 python 中)

ios - 将按钮选择器从单元格传递到 View Controller 的最佳方式

ios - 获取操作系统名称(例如 iOS)

ios - Heroku上具有Devise的Rails 3.2应用程序:无法使用Mobile Safari登录

swift - 3DES 加密结果与示例不同