2013-07-04 66 views
2

我正尝试使用CoreGraphics创建一个调色板(索引)PNG。创建调色板CGImageRef

我发现最好的是,我可以使用:

CGColorSpaceRef colorSpace = CGColorSpaceCreateIndexed(CGImageGetColorSpace(maskedImage), 255, <#const unsigned char *colorTable#>);

然后:

CGImageRef palettedImage = CGImageCreateCopyWithColorSpace(maskedImage, colorSpace)

但是我不知道该用什么作为的colorTable。我想利用一些预先制作的(快速)量化算法 - 例如在调用时已经内置到ImageIO的算法CGImageDestinationCreateWithURL(url, kUTTypeGIF , 1, NULL);

如何为PNG创建调色板?

回答

1

所以最终的解决办法是做这样的事情:

// Create an 8-bit palette for the bitmap via libimagequant (http://pngquant.org/lib) 
liq_attr *liqAttr = liq_attr_create(); 
liq_image *liqImage = liq_image_create_rgba(liqAttr, bitmap, (int)width, (int)height, 0); 
liq_result *liqRes = liq_quantize_image(liqAttr, liqImage); 

liq_write_remapped_image(liqRes, liqImage, bitmap, bytesPerRow * height); 
const liq_palette *liqPal = liq_get_palette(liqRes); 

// Transpose the result into an rgba array 
unsigned char colorTable[1024]; 
for (NSInteger n = 0; n < liqPal->count; n++) { 
    colorTable[4 * n] = liqPal->entries[n].r; 
    colorTable[4 * n + 1] = liqPal->entries[n].g; 
    colorTable[4 * n + 2] = liqPal->entries[n].b; 
    colorTable[4 * n + 3] = liqPal->entries[n].a; 
} 

// Release 
liq_attr_destroy(liqAttr); 
liq_image_destroy(liqImage); 
liq_result_destroy(liqRes); 

我的希望是使用该颜色表创建一个CGContextRef。但是,根据这篇文章:http://developer.apple.com/library/mac/#qa/qa1037/_index.html这是不可能在任何情况下。

+0

释放它之后使用调色板(将'liq_result_destroy(liqRes);'移动到底部)。你也可以使用'liqPal-> entries'作为颜色表,所以你甚至不需要复制操作。 – Kornel

1

如果你的色彩空间,例如RGB您将设置colorTable像这样:

{R, G, B, R, G, B, R, G, B, ...} 
+0

有没有办法自动生成颜色表? –

+0

有或没​​有你知道应该在你的颜色表中的颜色? – Danilo

+0

没有:)一些'自动魔术'。恐怕我自己的量化算法会太慢。 –