美文网首页
图片转gif

图片转gif

作者: PerhapYs | 来源:发表于2018-03-26 17:58 被阅读13次

// 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

      本文链接:https://www.haomeiwen.com/subject/qforcftx.html