我使用以下代码创建了 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然后 libpng或lodepng写入 PNG 文件。
关于macos - 如何创建 NSImage 的 8 位、4 位和 1 位表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18015884/