Skip to content

Instantly share code, notes, and snippets.

@mortenjust
Created July 22, 2022 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mortenjust/c13be29d713d60a53a73bb93452d3452 to your computer and use it in GitHub Desktop.
Save mortenjust/c13be29d713d60a53a73bb93452d3452 to your computer and use it in GitHub Desktop.
Remove alpha transparency from NSImage
extension NSImage {
func withoutAlpha() -> NSImage? {
// based on https://gist.github.com/mishimay/7b65167cf829e022f46dfa749d018661
guard let cgImage = self.cgImage(forProposedRect: nil, context: nil, hints: nil) else { return nil }
let context = CGContext(data: nil, width: cgImage.width, height: cgImage.height, bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: cgImage.bytesPerRow, space: cgImage.colorSpace!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: context.width, height: context.height))
guard let newCg = context.makeImage() else { return nil }
return NSImage(cgImage: newCg, size: .zero)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment