为什么 base64 格式的图像在 swift 3 中是白色的?

Why base64 renditions of images are white in swift 3?

我已经使用下面的代码转换了我的图像,这将 return 我的图像的 base64,但问题是当我将它们上传到服务器时,我只看到白色图像 - 你能建议我将图像转换为 base64 的更好方法,或者这是我选择的最佳方法 这是将图像转换为 base64

 func base64(from image: UIImage) -> String? {
    UIGraphicsBeginImageContext(image.size)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    let imageData = UIImageJPEGRepresentation(image!, 1.0)
    if let imageString = imageData?.base64EncodedString(options: .endLineWithLineFeed) {
        return imageString
    }
    return nil
}

它是白色的,因为当前上下文没有绘制任何东西!!!

你刚好 UIGraphicsBeginImageContext 尺码

并获得 UIGraphicsGetImageFromCurrentImageContext

它总是给你一个白色的图像,与Base64没有关系

如果你想渲染一些东西然后使用如下

        yourImageView.layer.render(in: UIGraphicsGetCurrentContext()!)

然后从 currentContext

获取图像

编辑

func base64(from image: UIImage) -> String? { 
   UIGraphicsBeginImageContext(image.size) 
   image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)) 
   let image = UIGraphicsGetImageFromCurrentImageContext() 
   UIGraphicsEndImageContext() 
   let imageData = UIImageJPEGRepresentation(image!, 1.0) 
   if let imageString = imageData?.base64EncodedString(options: .endLineWithLineFeed) { 
   return imageString 
   } 
    return nil 
  }

试试这个方法:

func convertImageToBase64(_ image:UIImage) -> String
  {
    let imageData = UIImageJPEGRepresentation(image, 1)//get imageData from image
    if(imageData != nil)
    {
      let Strbase64 = imageData?.base64EncodedString(options: .endLineWithCarriageReturn)//encode imageData
      return Strbase64!//return encoded string
    }
    return ""
  }

您向此方法传递了一个 UIImage,但从未对它执行任何操作,而是使用 UIGraphicsGetImageFromCurrentImageContext 创建了一个新的 UIImage,但您从未在该上下文中绘制任何内容。这就是为什么生成的图像是白色的。

但您根本不需要那些 UIGraphics 调用。只需获取您传递给此方法的 UIImage 的 JPEG 表示,并将其转换为 base 64 编码字符串:

func convertImageToBase64(_ image: UIImage) -> String? {
    return UIImageJPEGRepresentation(image, 1)?.base64EncodedString()
}

首先检查您遇到的错误是来自您的应用程序还是服务器端。您可以选择在线 base64 到图像转换器。复制您的 base64 字符串并先检查它们,您可以选择此 link

https://codebeautify.org/base64-to-image-converter