将 NSImage 保存为 PNG,没有字母和 5 位颜色



我有一个 NSImage,我想将其保存为 PNG,但删除 alpha 通道并使用 5 位颜色。 我目前正在这样做来创建我的 PNG:

NSData *imageData = [image TIFFRepresentation];
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
NSDictionary *imageProps = nil;
imageData = [imageRep representationUsingType:NSPNGFileType properties:imageProps];
[imageData writeToFile:fileNameWithExtension atomically:YES];

我已经阅读了很多关于SO的类似问题,但对最佳/正确的使用方法感到困惑。 我是否创建了一个新的CGGraphics上下文并绘制其中?我可以直接使用这些参数创建新的图像代表吗? 任何帮助,代码片段将不胜感激。

干杯

戴夫

我最终做到了。 看起来很丑,闻起来很臭。 任何更好的建议,非常感谢。

// Create a graphics context (5 bits per colour, no-alpha) to render the tile
static int const kNumberOfBitsPerColour = 5;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef tileGraphicsContext = CGBitmapContextCreate (NULL, rect.size.width, rect.size.height, kNumberOfBitsPerColour, 2 * rect.size.width, colorSpace, kCGBitmapByteOrder16Little | kCGImageAlphaNoneSkipFirst);
// Draw the clipped part of the image into the tile graphics context
NSData *imageData = [clippedNSImage TIFFRepresentation];
CGImageRef imageRef = [[NSBitmapImageRep imageRepWithData:imageData] CGImage];
CGContextDrawImage(tileGraphicsContext, rect, imageRef);
// Create an NSImage from the tile graphics context
CGImageRef newImage = CGBitmapContextCreateImage(tileGraphicsContext);
NSImage *newNSImage = [[NSImage alloc] initWithCGImage:newImage size:rect.size];
// Clean up
CGImageRelease(newImage);
CGContextRelease(tileGraphicsContext);
CGColorSpaceRelease(colorSpace);

最新更新