NSImage to NSBitmapImageRep

后端 未结 3 1826
暗喜
暗喜 2021-02-04 06:00

How to convert NSImage to NSBitmapImageRep? I have code:

- (NSBitmapImageRep *)bitmapImageRepresentation
{
    NSBitmapImageRep *ret = (NSBitmapImageRep *)[self          


        
3条回答
  •  伪装坚强ぢ
    2021-02-04 06:52

    Maybe late to the party, but this is the Swift 3 version from the @mrwalker response:

    extension NSImage {
        func bitmapImageRepresentation(colorSpaceName: String) -> NSBitmapImageRep? {
            let width = self.size.width
            let height = self.size.height
    
            if width < 1 || height < 1 {
                return nil
            }
    
            if let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(width), pixelsHigh: Int(height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: colorSpaceName, bytesPerRow: Int(width) * 4, bitsPerPixel: 32)
            {
                let ctx = NSGraphicsContext.init(bitmapImageRep: rep)
                NSGraphicsContext.saveGraphicsState()
                NSGraphicsContext.setCurrent(ctx)
                self.draw(at: NSZeroPoint, from: NSZeroRect, operation: NSCompositingOperation.copy, fraction: 1.0)
                ctx?.flushGraphics()
                NSGraphicsContext.restoreGraphicsState()
                return rep
            }
            return nil
        }
    }
    

提交回复
热议问题