2014-02-20 42 views
0

我有一個NSImage,我想保存爲PNG,但刪除Alpha通道並使用5位顏色。我目前這樣做是爲了創建我的PNG:保存NSImage爲無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嗎?任何幫助,與代碼片段將不勝感激。

乾杯

戴夫

回答

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