核心图形和GIF颜色表

Pat*_*ick 7 macos cocoa core-graphics gif

我试图限制动画GIF(从数组创建CGImageRef)的颜色数量.

但是,我实际上很难设置自定义颜色表.有谁知道如何使用Core Graphics做到这一点?

我知道kCGImagePropertyGIFImageColorMap.下面是一些测试代码(从这个github gist中大量借用- 因为它是kCGImagePropertyGIFImageColorMapGoogle 唯一可以找到的实例).

NSString *path = [@"~/Desktop/test.png" stringByExpandingTildeInPath];

CGDataProviderRef imgDataProvider = CGDataProviderCreateWithCFData((CFDataRef)[NSData dataWithContentsOfFile:path]);
CGImageRef image = CGImageCreateWithPNGDataProvider(imgDataProvider, NULL, true, kCGRenderingIntentDefault);

const uint8_t colorTable[ 8 ] = { 0, 0, 0, 0, 255, 255, 255 , 255};
NSData* colorTableData = [ NSData dataWithBytes: colorTable length: 8 ];
NSMutableDictionary *gifProps = [NSMutableDictionary dictionary];

[gifProps setObject:colorTableData forKey:(NSString *)kCGImagePropertyGIFImageColorMap];
[gifProps setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCGImagePropertyGIFHasGlobalColorMap];

NSDictionary* imgProps = [ NSDictionary dictionaryWithObject: gifProps 
                                                      forKey: (NSString*) kCGImagePropertyGIFDictionary ];

NSURL* destUrl = [NSURL fileURLWithPath:[@"~/Desktop/test.gif" stringByExpandingTildeInPath]];

CGImageDestinationRef dst = CGImageDestinationCreateWithURL( (CFURLRef) destUrl, kUTTypeGIF, 1, NULL );


CGImageDestinationAddImage( dst, image, imgProps );
CGImageDestinationSetProperties(dst, (CFDictionaryRef) imgProps);
CGImageDestinationFinalize( dst );
CFRelease( dst );
Run Code Online (Sandbox Code Playgroud)

然而,这不会产生黑白图像.

此外,我尝试打开GIF来查找颜色表信息,但这提供的帮助很少.

CGImageSourceRef imageSourceRef = CGImageSourceCreateWithURL((CFURLRef) destUrl, NULL);
NSDictionary *dict = (NSDictionary *)CGImageSourceCopyPropertiesAtIndex(imageSourceRef,0, NULL);
CGImageRef img = CGImageSourceCreateImageAtIndex(imageSourceRef, 0, NULL);

printf("Color space model: %d, indexed=%d, rgb = %d\n",  CGColorSpaceGetModel(CGImageGetColorSpace(img)), kCGColorSpaceModelIndexed,kCGColorSpaceModelRGB);
NSLog(@"%@", dict);
Run Code Online (Sandbox Code Playgroud)

它说GIF的颜色空间是RGB.然而,如果我使用索引的PNG尝试该代码,它表示颜色空间已编入索引.

此外,我尝试过的所有GIF都有一个图像字典,大致如下所示:

{
ColorModel = RGB;
Depth = 8;
HasAlpha = 1;
PixelHeight = 176;
PixelWidth = 314;
"{GIF}" =     {
    DelayTime = "0.1";
    UnclampedDelayTime = "0.04";
};
}
Run Code Online (Sandbox Code Playgroud)

(如果我使用CGImageSourceCopyProperties(...)它,它会提到一个全局颜色贴图,但同样没有提供颜色表.)

小智 2

我没有运行你的代码,但通过阅读它我看到一个错误:gif 中的颜色空间是rgb,所以你的颜色图应该有numcolors*3项目(而不是*4)。IOS 不能很好地处理大小不是 3 的倍数的颜色图...

换句话说:

const uint8_t colorTable[ 6 ] = { 0, 0, 0, 255, 255 , 255};
NSData* colorTableData = [ NSData dataWithBytes: colorTable length:6];
Run Code Online (Sandbox Code Playgroud)

应该做这项工作。