Mike Dong的博客

技术,工作,生活点滴

Gif编码

以前使用GifHub上的AnGif来转换,转换效率比较低,并且生成索引颜色的算法也比较粗糙。 后来改用系统的来实现,效率非常快,并且最后的Gif图非常接近mp4的视频。 主要就是使用系统的ImageIO和MobileCoreService.

make gif from images
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
NSUInteger kFrameCount = 16;
NSDictionary *fileProperties = @{
(id)kCGImagePropertyGIFDictionary: @{
(id)kCGImagePropertyGIFLoopCount: @0, // 0 means loop forever
}
};
NSDictionary *frameProperties = @{
(id)kCGImagePropertyGIFDictionary: @{
(id)kCGImagePropertyGIFDelayTime: @0.15f,
}
};
NSURL *fileURL = [NSURL fileURLWithPath:strPath];
CGImageDestinationRef destination = CGImageDestinationCreateWithURL((CFURLRef)fileURL, kUTTypeGIF, kFrameCount, NULL);
CGImageDestinationSetProperties(destination, (CFDictionaryRef)fileProperties);
for (NSUInteger i = 0; i < kFrameCount; i++)
{
@autoreleasepool
{
UIImage * image = #generate i index frame image#
CGImageDestinationAddImage(destination, image.CGImage, (CFDictionaryRef)frameProperties);
}
}
if (!CGImageDestinationFinalize(destination))
{
NSLog(@”failed to finalize image destination);
}
CFRelease(destination);

iOS