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

时间:2014-02-20 08:46:47

标签: png quartz-graphics nsimage nsimagerep

我有一个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上下文并将其绘制成?我可以直接使用这些参数创建新的imageRep吗?任何帮助,以及代码片段都将非常感激。

干杯

戴夫

1 个答案:

答案 0 :(得分:0)

我最后这样做了。看起来丑陋,闻起来像我。任何更好的建议都非常感谢。

// 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);