-1

I am using the following code on my IBAction to save my UIImageView to my gallery:

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

It works, but the image quality is not great, probably because it is a JPEG

How can I save as a PNG instead?

chuckbass
  • 95
  • 7
  • Why draw the image view? Why not save the image view's image? – rmaddy Dec 06 '18 at 22:16
  • Have you played around with the scale in UIGraphicsBeginImageContextWithOptions? Rendering the layer typically doesn't provide the best quality if my memory serves me well – Philip De Vries Dec 06 '18 at 23:23
  • For the PNG convert look here: https://stackoverflow.com/questions/1489250/uiimagewritetosavedphotosalbum-save-as-png-with-transparency – Philip De Vries Dec 06 '18 at 23:29

1 Answers1

-1

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)
            }
        }
Vishal Vaghasiya
  • 4,618
  • 3
  • 29
  • 40