核心图形和GIF颜色表
问题描述:
我想限制动画GIF(从数组CGImageRef
创建)的颜色数。核心图形和GIF颜色表
但是,我很难实际设置自定义颜色表。有谁知道如何用Core Graphics来做到这一点?我知道的kCGImagePropertyGIFImageColorMap
。以下是一些测试代码(从this github gist大量借用 - 因为它是Google可以找到的唯一的kCGImagePropertyGIFImageColorMap
实例)。
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(...)
,它提到一个全球性的彩色地图,但同样没有颜色表提供)。
答
我没有运行你的代码,但从阅读它,我看到一个错误:在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];
应该做的工作。
在标签中说OS X。 – uchuugaka 2015-01-20 04:46:40