Skip to content

Instantly share code, notes, and snippets.

@dagronf
Last active June 29, 2020 05:05
Show Gist options
  • Save dagronf/9992305d94977a74c874959c7467d669 to your computer and use it in GitHub Desktop.
Save dagronf/9992305d94977a74c874959c7467d669 to your computer and use it in GitHub Desktop.
An NSImage extension that converts an NSImage in ANY supported format to a new NSImage using the generic RGB colorspace.
extension NSImage {
/// An NSImage extension that converts an NSImage in ANY format to a new NSImage using the calibrated RGB colorspace.
///
/// Useful when you have to support a 3rd party tool that has format limitations, such as not supporting
/// paletted PNG files or grayscale colorspaces (I'm looking at you Create ML!)
func copyAsCalibratedRGBColorspace() -> NSImage? {
guard let rep = self.representations.first else {
return nil
}
let origSize = NSSize(width: rep.pixelsWide, height: rep.pixelsHigh)
let newRect = NSRect(x: 0, y: 0, width: origSize.width, height: origSize.height)
guard let representation =
NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(newRect.width),
pixelsHigh: Int(newRect.height),
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: .calibratedRGB,
bytesPerRow: 0,
bitsPerPixel: 0
) else {
return nil
}
representation.size = newRect.size
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: representation)
rep.draw(in: newRect, from: .zero, operation: .copy, fraction: 1.0, respectFlipped: true, hints: nil)
//self.draw(in: newRect, from: NSZeroRect, operation: .copy, fraction: 1.0)
NSGraphicsContext.restoreGraphicsState()
let newImage = NSImage(size: newRect.size)
newImage.addRepresentation(representation)
return newImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment