swift - 将图像编码为 base64 时的字符串无效 - Swift 4

标签 swift encoding base64 nsdata decoding

我的问题是,当我尝试将图像编码为 base-64 时,它会生成一个长字符串(最多 200,000 行),并且在解码中不起作用,它会生成一个 nil 图像!即使我尝试将图像调整为较小的尺寸,但仍然不起作用!

这是我的图像编码代码

let image = imageView.image
let imageData:NSData = UIImagePNGRepresentation(image!)! as NSData
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)

解码代码:

let processImage = user.value(forKey: "processImage") as! String // image from json 
if let dataDecoded:NSData = NSData(base64Encoded: processImage, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) {
          let image: UIImage = UIImage(data:dataDecoded as Data,scale:1.0)!
          print(image.size)
          self.myImage.image = image }

最佳答案

您可以尝试以下步骤:

步骤:- 1 首先从中获取 NSData

<小时/>

有三种可能性:

<强>1。使用图像名称

 let image : UIImage = UIImage(named:"imageNameHere")!
//Now use image to create into NSData format
let imageData:NSData = UIImagePNGRepresentation(image)!

<强>2。使用 NSURL:

//Use image's path to create NSData
let url:NSURL = NSURL(string : "urlHere")!
//Now use image to create into NSData format
let imageData:NSData = NSData.init(contentsOfURL: url)!

<强>3。从图像选择器中选取的图像

 let image = info[UIImagePickerControllerOriginalImage] as? UIImage    
 let imageData:NSData = UIImagePNGRepresentation(image)!
<小时/>

步骤:-2然后编码:

    let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
    print(strBase64)

步骤:-3然后解码:

    let dataDecoded : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
    let decodedimage = UIImage(data: dataDecoded)
    yourImageView.image = decodedimage

希望有帮助。

关于swift - 将图像编码为 base64 时的字符串无效 - Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49894145/

相关文章:

delphi - 在 TThread 中将 Jpeg 保存为 base64

ios - Realm 因 RLMException : object has been deleted or invalidated 崩溃

ubuntu - tr (ubuntu) 和 tr (mac) 之间的编码差异

javascript - Postman 上带有 base64 字符串的无效 JSON 数据

Java 处理国际文件。编码的东西

xslt - xslt-fo不支持utf-8吗?

database - 二进制数据的十六进制编码的目的是什么?

swift - 何时在 Swift 中使用委托(delegate)、输入输出或完成?

ios - 使用谷歌地图时出现错误,错误是 - libc++abi.dylib : terminating with uncaught exception of type NSException

iOS 如何为每个用户获取数据解析 Swift