图片转gif


// 1. 获取图片数据
    NSMutableArray *images = [[NSMutableArray alloc] initWithObjects:[UIImage imageNamed:@"1"], [UIImage imageNamed:@"2"],nil];
    // 2. 创建gif文件
    NSArray *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentStr = [document objectAtIndex:0];
    NSFileManager *filemanager = [NSFileManager defaultManager];
    NSString *testDic = [documentStr stringByAppendingString:@"/gif"];
    [filemanager createDirectoryAtPath:testDic withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *path = [testDic stringByAppendingString:@"test1.gif"];
    // 3.配置gif属性
    CGImageDestinationRef destion;
    CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)path, kCFURLPOSIXPathStyle, false);
    destion = CGImageDestinationCreateWithURL(url,kUTTypeGIF, images.count, NULL);
    NSDictionary *frameDic = [NSDictionary dictionaryWithObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:0.3],(NSString *)kCGImagePropertyGIFDelayTime, nil] forKey:(NSString *)kCGImagePropertyGIFDelayTime];
    NSMutableDictionary *gifParmdict = [NSMutableDictionary dictionaryWithCapacity:2];
    [gifParmdict setObject:[NSNumber numberWithBool:true] forKey:(NSString *)kCGImagePropertyGIFHasGlobalColorMap];
    [gifParmdict setObject:(NSString *)kCGImagePropertyColorModelRGB forKey:(NSString *)kCGImagePropertyColorModel];
    [gifParmdict setObject:[NSNumber numberWithInt:8] forKey:(NSString *)kCGImagePropertyDepth];
    [gifParmdict setObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount];

    NSDictionary *gifProperty = [NSDictionary dictionaryWithObject:gifParmdict forKey:(NSString *)kCGImagePropertyGIFDictionary];
    
    //  4. 单帧添加到gif
    for (UIImage *dicImage in images) {
        CGImageDestinationAddImage(destion, dicImage.CGImage, (__bridge CFDictionaryRef)frameDic);
    }
    CGImageDestinationSetProperties(destion, (__bridge_retained CFDictionaryRef)gifProperty);
    CGImageDestinationFinalize(destion);
    CFRelease(destion);
    
    NSLog(@"%@",path);

你可能感兴趣的:(图片转gif)