Swift-通过IBAction将UIImageView保存为PNG文件



我在IBAction上使用以下代码将UIImageView保存到我的库中:

UIGraphicsBeginImageContextWithOptions(self.theView.bounds.size, view.isOpaque, 0)
theView.layer.render(in: UIGraphicsGetCurrentContext()!)
let theCapturedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//UIImageWriteToSavedPhotosAlbum(theCapturedImage!,self,nil,nil)

它工作,但图像质量不是很好,可能是因为它是JPEG

如何保存为PNG?

Swift 4.2,Xcode 10.0

let fileManager = FileManager.default
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("scan.jpg")
DispatchQueue.global(qos: .background).async {
let image = UIImage(data: "Enter ImageData")
if image != nil {
let imageData = image!.pngData()
UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
DispatchQueue.main.async {
let alert = UIAlertController(title: "Success", message: "Image have been saved successfully!", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: { (action) in
let _ = self.navigationController?.popViewController(animated: true)
}))
self.present(alert, animated: true, completion: nil)
}
}
else {
let alert = UIAlertController(title: "Message", message: "Image not found", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel, handler: { (action) in
}))
self.present(alert, animated: true, completion: nil)
}
}

最新更新