Converting Image using pngdata causes app to freeze then crash

I'm using the following code to convert images to data to store them in core data, however its causing the app to crash due to running out of memory.


let imagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(mainPicName)
     if fileManager.fileExists(atPath: imagePath) {
          DispatchQueue.main.async {
               if let image : UIImage = UIImage(contentsOfFile: imagePath) {
                    let imageData = image.pngData()
               }
     }
}

If I comment out the let imageData = image.pngData() line then I don't get the issue

With the line commented out, the memory usage once the app has loaded is less than 100MB, if its not commented it can get to 2GB before crashing

How big is your image and in which format?


Note that UIImage is just an opaque container that does not necessarily hold your image in memory. Only when you actually require the image data it is loaded from the underlying provider.

The sizes vary, they come from either the camera or the photo library. Formats may vary as well

You could write a custom class to archive your image data which might reduce the size. I have an example I could share if you like?
Converting Image using pngdata causes app to freeze then crash
 
 
Q