0

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.

RockOdil
  • 1
  • 2
  • Why do you needlessly try to get the PNG data of an image and then create a new image from that data? Just pass `imageView.image` to `UIImageWriteToSavedPhotosAlbum`. And note that `UIImageWriteToSavedPhotosAlbum` requires the "Privacy - Photo Library Additions Usage Description" entry in Info.plist under iOS 11. – rmaddy Feb 15 '18 at 15:05
  • Many thanks! It worked. Did this, because it is my first Swift program and read some tutorials about this. – RockOdil Feb 15 '18 at 15:27

1 Answers1

1

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

John Snow
  • 452
  • 3
  • 5
  • Yes, have read this. But the question is, what is data? The luminance values of the pixels? They are generated by the model-output of the neural net from CoreML. I do not load an image from a file like in this post: https://stackoverflow.com/questions/28846705/uiimagepngrepresentationuiimage-returns-nil I wonder because the result-image is dispayed correctly, so it should contain data? – RockOdil Feb 15 '18 at 14:38