【问题标题】:Create Paletted CGImageRef创建调色板 CGImageRef
【发布时间】:2013-07-02 22:44:44
【问题描述】:

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

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

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

然后:

CGImageRef palettedImage = CGImageCreateCopyWithColorSpace(maskedImage, colorSpace)

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

如何为 PNG 创建调色板?

【问题讨论】:

    标签: objective-c core-graphics png-8


    【解决方案1】:

    如果您的色彩空间是例如 RGB,您可以像这样设置 colorTable:

    {R, G, B, R, G, B, R, G, B, ...}
    

    【讨论】:

    • 有没有办法自动生成色表?
    • 您是否知道颜色表中应包含的颜色?
    • 没有 :) 一些“自动魔法”。恐怕我自己的量化算法会太慢。
    • 我认为 sdk 无法为您做到这一点。我不知道。但是您可以使用像 pngquant.org/lib 这样的库来进行转换。
    【解决方案2】:

    所以最终的解决方案是这样做:

    // 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,这在任何情况下都是不可能的。

    【讨论】:

    • 您在释放调色板后正在使用它(将liq_result_destroy(liqRes); 移至底部)。你也可以使用liqPal-&gt;entries作为颜色表,所以你甚至不需要复制操作。
    猜你喜欢
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多