gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:34:38 27 4
gpt4 key购买 nike

我的问题是,当我尝试将图像编码为 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com