【发布时间】: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