How to save an Image to NsData object and then retrieve.

My environment is as follows:

Xcode 12, macOS BS developing a macOS app.

I have an IBOutlet from a IB window as @IBOutlet weak var imageView: NSImageView!

So, I want to store imageView to a NSData object and then save the NSData object in my UserDefaults.

Once I saved the Image in my UserDefaults I need to be able to decode or retrieve the image for use in other parts of the app.

How is this done?

Also, I have seen some cautions about converting an Image to NSData object and retrieving. It seems the retrieved image may not be 100% as it was originally. Is this true and if so why?

Thanks

So, I want to store imageView to a NSData object and then save the NSData object in my UserDefaults.

Saving an image in user defaults is not a great plan. User defaults is intended to be used for preserving small preferences. While it can handle larger items, it doesn’t work well for that. It would be much better to save this to a file. If necessary you can store a reference to that file in user defaults.

It seems the retrieved image may not be 100% as it was originally.

That depends on how you save it. The two most common options are:

  • JPEG, which is inherently lossy

  • PNG, which is lossless, but you could still lose quality if the source image has wide colour

Anyway, as to how you convert an NSImage to NSData, the standard approach is to get the bitmap image representation (NSBitmapImageRep) from the image and then use its conversion routines.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Thanks, for your answer.. I have decided to save the image to a file.

How to save an Image to NsData object and then retrieve.
 
 
Q