gpt4 book ai didi

ios - Base64 图像编码 Swift 4 iOS

转载 作者:行者123 更新时间:2023-11-28 12:16:38 25 4
gpt4 key购买 nike

我有以下代码可以从库中选择一个图像,然后进行 base64encode 以供将来上传...图像被选中并显示在我想要的应用程序中...但是在输出中我得到了这个错误

[发现] 发现扩展时遇到的错误:Error Domain=PlugInKit Code=13 "query cancelled"UserInfo={NSLocalizedDescription=query cancelled}

如果我在输出中使用打印的 base64 代码并使用网络工具 ( https://www.base64decode.org/ ) 尝试解码所述信息,以确认它有效,然后我开始在 iOS 中解码 - 它似乎是畸形?我假设我仍然没有正确编码图像?

 @IBAction func selectImage(_ sender: AnyObject) {


selectImage.allowsEditing = true //2
selectImage.sourceType = .photoLibrary //3
present(selectImage, animated: true, completion: nil)//4


}

func imagePickerController(_ selectImage: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {


let chosenImage = info[UIImagePickerControllerEditedImage] as! UIImage //2

profilePic.contentMode = .scaleAspectFit //3
profilePic.image = chosenImage //4

let quality = 1.0
base64String = (UIImageJPEGRepresentation(chosenImage, CGFloat(quality))?.base64EncodedString())!
print (base64String)

self.dismiss(animated: true, completion: nil) //5
}

最佳答案

我在我的项目中使用了这两个函数,并且运行良好。

 func imageTobase64(image: UIImage) -> String {
var base64String = ""
let cim = CIImage(image: image)
if (cim != nil) {
let imageData = image.highQualityJPEGNSData
base64String = imageData.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength64Characters)
}
return base64String
}

func base64ToImage(base64: String) -> UIImage {
var img: UIImage = UIImage()
if (!base64.isEmpty) {
if let decodedData = Data(base64Encoded: base64 , options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) as Data {
let decodedimage = UIImage(data: decodedData)
img = (decodedimage as UIImage?)!
}

}
return img
}

我还有一个处理图像质量的扩展,它很有用:

  extension UIImage {
var highestQualityJPEGNSData:NSData { return UIImageJPEGRepresentation(self, 1.0)! as NSData }
var highQualityJPEGNSData:NSData { return UIImageJPEGRepresentation(self, 0.75)! as NSData}
var mediumQualityJPEGNSData:NSData { return UIImageJPEGRepresentation(self, 0.5)! as NSData }
var lowQualityJPEGNSData:NSData { return UIImageJPEGRepresentation(self, 0.25)! as NSData}
var lowestQualityJPEGNSData:NSData { return UIImageJPEGRepresentation(self, 0.0)! as NSData }
}

//对于 Swift 4.2 - 修改后的扩展

extension UIImage {
var highestQualityJPEGNSData:NSData { return self.jpegData(compressionQuality: 1.0)! as NSData }
var highQualityJPEGNSData:NSData { return self.jpegData(compressionQuality: 0.75)! as NSData}
var mediumQualityJPEGNSData:NSData { return self.jpegData(compressionQuality: 0.5)! as NSData }
var lowQualityJPEGNSData:NSData { return self.jpegData(compressionQuality: 0.25)! as NSData}
var lowestQualityJPEGNSData:NSData { return self.jpegData(compressionQuality: 0.0)! as NSData }
}

关于ios - Base64 图像编码 Swift 4 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46304641/

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