编码图像到base64的无效字符串 - Swift 4

时间:2018-04-18 07:53:38

标签: swift encoding base64 nsdata decoding

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

这是我的图片编码

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 个答案:

答案 0 :(得分:0)

您可以尝试以下步骤:

步骤: - 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

希望它有所帮助。