macos - 如何创建 NSImage 的 8 位、4 位和 1 位表示

标签 macos cocoa nsimage nsbitmapimagerep

我使用以下代码创建了 32 位 NSImage。

 NSBitmapImageRep *sourceRep = [[NSBitmapImageRep alloc] initWithData: imageData];

        // create a new bitmap representation scaled down

            NSBitmapImageRep *newRep = 
                [[NSBitmapImageRep alloc] 
                    initWithBitmapDataPlanes: NULL
                    pixelsWide: imageSize
                    pixelsHigh: imageSize
                    bitsPerSample: 8
                    samplesPerPixel: 4
                    hasAlpha: YES
                    isPlanar: NO
                    colorSpaceName: NSCalibratedRGBColorSpace
                    bytesPerRow: 0
                    bitsPerPixel: 0];

            // save the graphics context, create a bitmap context and set it as current
            [NSGraphicsContext saveGraphicsState] ;
            NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep: newRep];
            [NSGraphicsContext setCurrentContext: context] ;

            // draw the bitmap image representation in it and restore the context
            [sourceRep drawInRect: NSMakeRect(0.0f, 0.0f, imageSize, imageSize)] ;
            [NSGraphicsContext restoreGraphicsState] ;

            // set the size of the new bitmap representation
            [newRep setSize: NSMakeSize(imageSize,imageSize)] ;

            NSDictionary *imageProps2 = [NSDictionary dictionaryWithObjectsAndKeys:
                                         [NSNumber numberWithFloat:1.0], kCGImageDestinationLossyCompressionQuality,
                                         nil];
            imageData = [newRep representationUsingType: NSPNGFileType properties: imageProps2];
  NSImage *bitImage  = [[NSImage alloc]initWithData:imageData];

现在我需要创建 8 位(256 色)、4 位(16 色)、1 位(黑白)NSBitmapImageRep 表示。我现在想做什么?

最佳答案

不幸的是,Cocoa 似乎不支持对调色板图像进行操作。

我去过trying that before我的结论是,这对巴布亚新几内亚来说是不可能的。 NSGIFFileType 是一个硬编码异常,图形上下文是 even more limited比位图表示形式(例如,仅预乘 alpha 支持 RGBA)。

为了解决这个问题,我 convert NSBitmapImageRep to raw RGBA bitmap ,使用libimagequant to remap it to a palette然后 libpnglodepng写入 PNG 文件。

关于macos - 如何创建 NSImage 的 8 位、4 位和 1 位表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18015884/

相关文章:

macos - flutter 医生 : ERROR: Could not connect to lockdownd, 错误代码 -21

objective-c - NSOutlineView 中文件夹和子文件夹的对象模型

objective-c - 在 XCode 中更改 NSImage - 这行代码不起作用

ios - 使用 UIImageJPEGRepresentation 时,多少数字可以保留完整分辨率?

ios - 用实例方法和类方法进行初始化

xcode - 在 Xcode 中自动插入右括号

Python 多处理故障排除

objective-c - Mac 编程 : Command-TAB - How does this build the application list?

swift - 如何将 X 帧混合到一帧以获得运动模糊?

objective-c - 是否可以检查存储在 NSimage 对象中的图像是否为灰度图像?