Last active
June 29, 2020 05:05
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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