0

In iOS I can store UIImage to an app group as Data. I can convert the png image with pngData() to a Data object:

let imageData = scaledImage.pngData()!

I store that object in an app group, retrieve it and convert ik back to an UIImage:

let image = UIImage(data: imageData)

It's works great, but it doesn't work on macOS. MacOS doesn't have a UIImage, but a NSImage. How can I convert an NSImage tot Data and back?

Update: I use this code for macOS

let image = NSImage(named: "axl")! 
let imageData = image.tiffRepresentation!

I store the imageData in a array.

In another part of the code I get the imageData from the array and convert it back:

let imageData = entry.images[0]                     
let image = NSImage(data: imageData)
                                    

Somehow the tiffRepresentation converting back with NSImage(data: ...) doesn't work.

Update: it does work!!

  • Does this answer your question? [NSImage to NSData as PNG Swift](https://stackoverflow.com/questions/29262624/nsimage-to-nsdata-as-png-swift) – Andrew Nov 01 '22 at 12:36
  • I found this answer but was not able to get it working. As I understand I can use: let imageData = imageAXL.tiffRepresentation! to convert png to data. That seems to work, but how can I convert data to png again? It's not clear for me in that answer. Can you help me out here? Would be nice. – Patrick Koning Nov 02 '22 at 12:59
  • You can init an NSImage using `NSImage(data:)` https://developer.apple.com/documentation/appkit/nsimage/1519941-init – Andrew Nov 02 '22 at 13:31
  • Thx for you help ;) I updated the question with de macOS code. Do you have a clue what's going wrong? – Patrick Koning Nov 02 '22 at 16:13
  • Hi, after testing the code alone (without all the other code) it works indeed ;) Thx, for you help. It made me focus on the right thing and found out that there was another problem in SwiftUI-code. – Patrick Koning Nov 02 '22 at 16:51

1 Answers1

0

I use this code for macOS

let image = NSImage(named: "axl")! 
let imageData = image.tiffRepresentation!

I store the imageData in a array.

In another part of the code I get the imageData from the array and convert it back:

let imageData = entry.images[0]                     
let image = NSImage(data: imageData)                           

It does work!!