RockOdil
RockOdil

Reputation: 1

Saving an UIImage when UIImagePNGRepresentation always returns nil

I want to save the model-output of my CoreML model to the gallery. It outputs an MLMultiArray, which is converted to a UIImage to display the result image on the device. Now i want to save that image to the memory of the phone. "Privacy - Photo Library Usage Description" and "Privacy - Media Library Description" in the Info.plist is present. Have found some similar questions but could not solve the problem. I tried the following function:

func saveImage() {
    let imageData = UIImagePNGRepresentation(imageView.image!)
    let compressedImage = UIImage(data: imageData!)
    UIImageWriteToSavedPhotosAlbum(compressedImage!, nil, nil, nil)
    let alert = UIAlertController(title: "Saved", message: "Your image has been saved", preferredStyle: .alert)
    let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
    alert.addAction(okAction)
    self.present(alert, animated: true, completion: nil)
}

The problem is, that the result image of the model-output is always displayed on the device, but when i try to save the image, contained in imageView.image, the function UIImagePNGRepresentation() always returns nil.

Upvotes: 0

Views: 1685

Answers (1)

John Snow
John Snow

Reputation: 462

From Apples documentation:

func UIImagePNGRepresentation(_ image: UIImage) -> Data?

This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.

https://developer.apple.com/documentation/uikit/1624096-uiimagepngrepresentation

Upvotes: 1

Related Questions