1

In my iOS project, in order to count bytes for my png image called "toto" I use this line below in the console:

print(UIImage(imageLiteralResourceName: "toto").pngData()!.count)

But for my MacOS project, UIImage cannot be used so what equivalent can I use to achieve the same result?

Thanks.

Wild8x
  • 459
  • 4
  • 13
  • What are you trying to do with the resulting information?The byte count can vary drastically dependng on the format you're measuring. – Alexander Oct 23 '20 at 23:30
  • I understand that i would find different results depending on the format. In a group of images I incerted many identical empty png images 1px X 1px with normal images. I just wanted to display the normale images that are not empty. By using the answers it works fine. – Wild8x Oct 25 '20 at 05:03
  • That sounds ... strange. You should consider posting it to codereview.stackexchange.come – Alexander Oct 25 '20 at 13:57

2 Answers2

2

As you probably already noticed there is no pngData method for NSImage. You need to first get the image tiffRepresentation, initialize a new NSBitmapImageRep object and get the png storageType representation:


let data = NSBitmapImageRep(data: NSImage(imageLiteralResourceName: "toto").tiffRepresentation!)!.representation(using: .png, properties: [:])!
print(data.count)
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Thank you Leo for telling me to start with tiff and then use png. – Wild8x Oct 23 '20 at 22:37
  • Thank you Leo for telling me to start with tiff and then use png. For the same image the count result is for iOS (3553) => print(UIImage(imageLiteralResourceName: "toto").pngData()!.count) // for MacOS with tiff only (9360) => print(NSImage(imageLiteralResourceName: "toto").tiffRepresentation!.count) // and for MacOS with tiff+png (3463) => print(NSBitmapImageRep(data: NSImage(imageLiteralResourceName: "image1Min").tiffRepresentation!)!.representation(using: .png, properties: [:])!) // Anyway I just needed to count for my project . Thanks Rui and Leo. – Wild8x Oct 23 '20 at 22:44
1

MacOS equivalente of UIImage is NSImage

edit:

Here is something similar. Seems that you need to get a NSBitmapImageRep and then use NSBitmapImageRep.representation(using: .png, properties: [:])

Rui Rodrigues
  • 382
  • 5
  • 20
  • Thank you so much for giving me this answer that allows me to find a close equivalent (I could not find the png option but at least with the tiff option I could count and that is what I needed: print(NSImage(imageLiteralResourceName: "toto").tiffRepresentation!.count) – Wild8x Oct 23 '20 at 22:24
  • your last edit based on my post makes my answer pointless – Leo Dabus Oct 23 '20 at 22:40