【问题标题】:Core Graphics & GIF Color Table核心图形和 GIF 颜色表
【发布时间】:2011-05-27 03:51:21
【问题描述】:

我正在尝试限制动画 GIF 的颜色数量(从 CGImageRef 的数组创建)。

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

我知道kCGImagePropertyGIFImageColorMap。下面是一些测试代码(大量借鉴this github gist——因为它是kCGImagePropertyGIFImageColorMap Google 可以找到的唯一实例)。

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

但是,这不会产生黑白图像。

此外,我尝试打开 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);

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

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

{
ColorModel = RGB;
Depth = 8;
HasAlpha = 1;
PixelHeight = 176;
PixelWidth = 314;
"{GIF}" =     {
    DelayTime = "0.1";
    UnclampedDelayTime = "0.04";
};
}

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

【问题讨论】:

    标签: cocoa macos core-graphics gif


    【解决方案1】:

    我没有运行你的代码,但是通过阅读它我发现了一个错误: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];
    

    应该做的工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多