Convert white pixels to transparency in NSImage / Swift - how to improve?

126 Views Asked by At

I've been trying to find a good way to convert white pixels in an NSImage on the fly to transparent pixels. I've seen Swift examples for UIImage, but not NSImage. Below is what I've created (and which is working). Two questions:

  • Is there a better way to lose the alpha channel on an NSImage? I'm now converting it first to the JPEG representation (which doesn't have an alpha channel) and then to another representation again. That feels rather ugly

  • Is there a method / way to only trim white pixels on the edges of the images (not on the 'inside' of an image?


func mask(color: NSColor, tolerance: CGFloat = 4) -> NSImage {
    guard let data = tiffRepresentation,
          // This is an extremely ugly hack to strip the alpha channel from a bitmap representation (because maskingColorComponents does not want an alpha channel)
          // https://stackoverflow.com/questions/43852900/swift-3-cgimage-copy-always-nil
          // https://stackoverflow.com/questions/36770611/replace-a-color-colour-in-a-skspritenode
            let rep = NSBitmapImageRep(data: (NSBitmapImageRep(data: data)?.representation(using: .jpeg, properties: [:])!)!) else {
              return self
    }
    
    if let ciColor = CIColor(color: color) {
        NSLog("trying to mask image")
        let maskComponents: [CGFloat] = [ciColor.red, ciColor.green, ciColor.blue].flatMap { value in
            [(value * 255) - tolerance, (value * 255) + tolerance]
        }
        
        guard let masked = rep.cgImage(forProposedRect: nil, context: nil, hints: nil)?.copy(maskingColorComponents: maskComponents) else { return self }
        return NSImage(cgImage: masked, size: size)
    }

    return self
}
0

There are 0 best solutions below