4

I know I can use "UIImagePNGRepresentation(UIImagexxx)" to get the png representation of a UIImage object. But I'm not sure how I can do something similar for NSImage. I could only find TIFFRepresentation available for NSImage objects.

Any ideas? Thanks a lot

Yoope
  • 1,745
  • 2
  • 16
  • 22
  • See here: http://stackoverflow.com/questions/17507170/how-to-save-png-file-from-nsimage-retina-issues – qwerty_so Jan 27 '15 at 13:24
  • Thanks Thomas. I'm now working on it. I'm not clear why I cannot use the function like "representationUsingType( NSBitmapFileType.NSPNGFileType, properties: nil) " It says that [NSObject: AnyObject] does not conform to protocol "NilLiteralConvertible". I searched on google about this but it seems that I should be able to use it as metioned above. Do you know why this happens ? Thanks – Yoope Jan 28 '15 at 03:24
  • You should open a new question and post the code. It has to do with optionals but hard to tell in a short comment. – qwerty_so Jan 28 '15 at 10:05

1 Answers1

3

To help with cross-platform code, I implemented a version ofUIImagePNGRepresentation() that runs on Mac (and uses NSImage):

#if os(macOS)

public func UIImagePNGRepresentation(_ image: NSImage) -> Data? {
    guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil)
        else { return nil }
    let imageRep = NSBitmapImageRep(cgImage: cgImage)
    imageRep.size = image.size // display size in points
    return imageRep.representation(using: .png, properties: [:])
}

#endif
Robin Stewart
  • 3,147
  • 20
  • 29