做過一個與 GIF 相關的 App,一直沒時間記錄,現在把學習過程整理出來。核心觀念是:GIF 的讀與寫都建立在 ImageIO.framework 上,因此第一步永遠是先把這個 framework 加入專案。
- (void)viewDidLoad {
[super viewDidLoad];
NSData *data = [NSData dataWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:@"test101" ofType:@"gif"]];
// 由 data 取得圖像資料源
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
// 取得幀數
size_t count = CGImageSourceGetCount(source);
NSMutableArray *tmpArray = [NSMutableArray array];
for (size_t i = 0; i < count; i++) {
// 取出第 i 幀
CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, i, NULL);
UIImage *image = [UIImage imageWithCGImage:imageRef
scale:[UIScreen mainScreen].scale
orientation:UIImageOrientationUp];
[tmpArray addObject:image];
CGImageRelease(imageRef);
}
CFRelease(source);
int i = 0;
for (UIImage *img in tmpArray) {
// 逐張寫檔
NSData *imageData = UIImagePNGRepresentation(img);
NSString *pathNum = [[self backPath] stringByAppendingPathComponent:
[NSString stringWithFormat:@"%d.png", i]];
[imageData writeToFile:pathNum atomically:NO];
i++;
}
}
// 回傳存放圖片的路徑
- (NSString *)backPath {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *path = [UniversalMethod backDocumentDirectoryPath];
NSString *imageDirectory = [path stringByAppendingPathComponent:@"Normal"];
[fileManager createDirectoryAtPath:imageDirectory
withIntermediateDirectories:YES
attributes:nil
error:nil];
return imageDirectory;
}
流程是:CGImageSourceCreateWithData 建立資料源 → CGImageSourceGetCount 取得幀數 → CGImageSourceCreateImageAtIndex 逐幀取出 → 轉成 UIImage → 寫成 PNG。
合成時除了 ImageIO,還需要 MobileCoreServices.framework,因為 kUTTypeGIF 這個 UTI 常數定義在其中。
// 準備來源圖片
NSMutableArray *imgs = [[NSMutableArray alloc] initWithObjects:
[UIImage imageNamed:@"bear_1"],
[UIImage imageNamed:@"bear_2"], nil];
// 建立輸出路徑
NSArray *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentStr = [document objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *textDirectory = [documentStr stringByAppendingPathComponent:@"gif"];
[fileManager createDirectoryAtPath:textDirectory
withIntermediateDirectories:YES
attributes:nil
error:nil];
NSString *path = [textDirectory stringByAppendingPathComponent:@"test101.gif"];
NSLog(@"%@", path);
/*
CFURLCreateWithFileSystemPath(allocator, filePath, pathStyle, isDirectory)
allocator : 配置器,通常使用 kCFAllocatorDefault
filePath : 檔案路徑
pathStyle : 路徑風格,此處填 kCFURLPOSIXPathStyle
isDirectory : 是否為目錄路徑
*/
CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
(CFStringRef)path,
kCFURLPOSIXPathStyle,
false);
// 由 url 建立圖像輸出目標
CGImageDestinationRef destination;
destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, imgs.count, NULL);
// 單幀屬性:設定播放間隔
NSDictionary *frameProperties = [NSDictionary dictionaryWithObject:
[NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:0.3], (NSString *)kCGImagePropertyGIFDelayTime, nil]
forKey:(NSString *)kCGImagePropertyGIFDictionary];
// 整體屬性
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];
[dict setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCGImagePropertyGIFHasGlobalColorMap];
[dict setObject:(NSString *)kCGImagePropertyColorModelRGB forKey:(NSString *)kCGImagePropertyColorModel];
[dict setObject:[NSNumber numberWithInt:8] forKey:(NSString *)kCGImagePropertyDepth];
[dict setObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount];
NSDictionary *gifProperties = [NSDictionary dictionaryWithObject:dict
forKey:(NSString *)kCGImagePropertyGIFDictionary];
// 逐幀加入
for (UIImage *dImg in imgs) {
CGImageDestinationAddImage(destination, dImg.CGImage, (__bridge CFDictionaryRef)frameProperties);
}
CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)gifProperties);
CGImageDestinationFinalize(destination);
CFRelease(destination);
幾個關鍵參數值得解釋。kCGImagePropertyGIFDelayTime 是「每幀停留幾秒」,0.3 就是約每秒 3.3 幀;這個值放在 frameProperties 中,代表每幀可各自設定不同時長。kCGImagePropertyGIFLoopCount 為 0 代表無限迴圈,若要播放三次就填 3。kCGImagePropertyDepth 是色深,8 對應 GIF 的 256 色。
最後提醒記憶體管理:CGImageSourceRef、CGImageRef、CGImageDestinationRef、CFURLRef 全都是 Core Foundation 物件,遵循 Create Rule,用完必須 CFRelease 或 CGImageRelease。在 ARC 環境下 CF 物件不會被自動管理,這是最常見的洩漏來源。