iOS下视频转GIF

项目有一个新需求.需要选取一段视中的一段生成GIF图.整个过程中踩了不少坑,在此贴出来给需要的朋友
寻找方案当初借鉴了他人代码,但是忘记来源.如果有异议请随时联系保证第一时间删除

首先核心类是AVKit中的AVAsset和AVAssetImageGenerator.

AVAsset是苹果在iOS4.0-10.0中的音视频框架中的对象类,从相册中取出的对象就是AVAsset.

AVAssetImageGenerator是一个可以从AVAsset中获取某一个时间点的一张图的类.

AVKit框架在8.0后更新为了Photos框架.但是相关代码未找到.估未更新.

文章最下方会贴完整代码

核心思想:创建一个集合,其中包含了N个帧所在时间段的对象,然后循环集合,取出每个对象.根据对象所在的时间生成图片,将所有图片拼接为一个GIF图->生成本地GIF文件

处理帧对象方法

- (void)createGIFfromURL:(NSURL*)videoURL loopCount:(int)loopCount startSecond:(float)fltStartSecond delayTime:(CGFloat)delayTime gifTime:(float)fltGifTime gifImagePath:(NSString *)imagePath{
    
    NSDictionary *fileProperties = [self filePropertiesWithLoopCount:loopCount];
    NSDictionary *frameProperties = [self framePropertiesWithDelayTime:delayTime];
    
    AVURLAsset *asset = [AVURLAsset assetWithURL:videoURL];
    
    float videoWidth = [[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] naturalSize].width;
    float videoHeight = [[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] naturalSize].height;
    
    GIFSize optimalSize = GIFSizeMedium;
    if (videoWidth >= 1200 || videoHeight >= 1200)
        optimalSize = GIFSizeVeryLow;
    else if (videoWidth >= 800 || videoHeight >= 800)
        optimalSize = GIFSizeLow;
    else if (videoWidth >= 400 || videoHeight >= 400)
        optimalSize = GIFSizeMedium;
    else if (videoWidth < 400|| videoHeight < 400)
        optimalSize = GIFSizeHigh;
    
    
    int frameCount = fltGifTime * kFrameInSecond;
    
    //两帧的时间间隔
    float increment = (float)fltGifTime/frameCount;
    
    // Add frames to the buffer
    NSMutableArray *timePoints = [NSMutableArray array];
    for (int currentFrame = 0; currentFrame<frameCount; ++currentFrame) {
        float seconds = fltStartSecond + (float)increment * currentFrame;
        CMTime time = CMTimeMakeWithSeconds(seconds, 1 *NSEC_PER_SEC);
        [timePoints addObject:[NSValue valueWithCMTime:time]];
    }
    
    [self createGIFforTimePoints:timePoints fromURL:videoURL fileProperties:fileProperties frameProperties:frameProperties gifImagePath:imagePath frameCount:frameCount gifSize:optimalSize];
}

方法的核心是生成多个关键帧的时间并添加进一个数组.供后续生成图片使用

- (NSURL *)createGIFforTimePoints:(NSArray *)timePoints fromURL:(NSURL *)url fileProperties:(NSDictionary *)fileProperties  frameProperties:(NSDictionary *)frameProperties gifImagePath:(NSString *)imagePath frameCount:(int)frameCount gifSize:(GIFSize)gifSize{
    
    NSURL *fileURL = [NSURL fileURLWithPath:imagePath];
    if (fileURL == nil)
        return nil;
    
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypeGIF , frameCount, NULL);
    CGImageDestinationSetProperties(destination, (CFDictionaryRef)fileProperties);
    
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
    generator.appliesPreferredTrackTransform = YES;
    
    generator.requestedTimeToleranceBefore = kCMTimeZero;
    generator.requestedTimeToleranceAfter = kCMTimeZero;
    
    NSError *error = nil;
    CGImageRef previousImageRefCopy = nil;
    CGImageRef imageRef;
    NSLog(@"starat");
    
    
    
    for (NSValue *time in timePoints) {
        imageRef = [generator copyCGImageAtTime:[time CMTimeValue] actualTime:nil error:&error];
        if((float)gifSize/10 != 1){
            imageRef = createImageWithScale(imageRef, (float)gifSize/10);
        }
        
        if (error) {
            _error =error;
            NSLog(@"Error copying image: %@", error);
            return nil;
            
        }
        if (imageRef) {
            CGImageRelease(previousImageRefCopy);
            previousImageRefCopy = CGImageCreateCopy(imageRef);
        } else if (previousImageRefCopy) {
            imageRef = CGImageCreateCopy(previousImageRefCopy);
        } else {
            _error =[NSError errorWithDomain:NSStringFromClass([self class]) code:0 userInfo:@{NSLocalizedDescriptionKey:@"Error copying image and no previous frames to duplicate"}];
            NSLog(@"Error copying image and no previous frames to duplicate");
            return nil;
        }
        CGImageDestinationAddImage(destination, imageRef, (CFDictionaryRef)frameProperties);
        CGImageRelease(imageRef);
    }
    NSLog(@"end");
    CGImageRelease(previousImageRefCopy);
    
    // Finalize the GIF
    if (!CGImageDestinationFinalize(destination)) {
        
        _error =error;
        
        NSLog(@"Failed to finalize GIF destination: %@", error);
        if (destination != nil) {
            CFRelease(destination);
        }
        return nil;
    }
    CFRelease(destination);
    
    return fileURL;
}

根据每一帧所在的时间去生成图片.组合成一个GIF.
总体功能是实现了.但是效率有些低下.24帧/s的一个GIF 3s生成需要大概20s.所有这块儿还是需要进行优化的

//
//  GIFGenerator.m
//  GIFGenerator
//
//  Created by 侯志桐Work on 2018/7/19.
//  Copyright © 2018年 BlackMonkey. All rights reserved.
//

#import "GIFGenerator.h"
#import <AVKit/AVKit.h>
#import <MobileCoreServices/UTCoreTypes.h>

//typedef NS_ENUM(NSInteger, GIFSize) { GIFSizeVeryLow = 2, GIFSizeLow = 3, GIFSizeMedium = 5, GIFSizeHigh = 7, GIFSizeOriginal = 10 };

typedef NS_ENUM(NSInteger, GIFSize) { GIFSizeVeryLow = 1, GIFSizeLow = 2, GIFSizeMedium = 3, GIFSizeHigh = 5, GIFSizeOriginal = 10 };

//动画1s多少帧
#define kFrameInSecond (24)


@interface GIFGenerator()

@property (nonatomic,strong)NSError *error;

@end
@implementation GIFGenerator

+(instancetype)shareGIFGenerator{
    static GIFGenerator *generator;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        generator = [[self alloc] init];
    });
    return generator;
}


- (void)generatorGIFWithLocalVideoPath:(NSString *)strVideoPath startSecond:(float)startSecond gifTime:(float)gifTime gifFilePath:(NSString *)gifFilePath completeBlock:(void(^)(BOOL isSuccess,NSError *error))completeBlock{
    self.error = nil;
    if(![[NSFileManager defaultManager] fileExistsAtPath:strVideoPath]){
        if(completeBlock){
            completeBlock(NO,[[NSError alloc] initWithDomain:NSURLErrorDomain code:-1 userInfo:@{@"msg":@"文件不存在"}]);
        }
        return;
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSURL *videoUrl = [NSURL fileURLWithPath:strVideoPath];
        CGFloat delayTime = 1.f / kFrameInSecond;
        [self createGIFfromURL:videoUrl loopCount:1 startSecond:startSecond delayTime:delayTime gifTime:gifTime gifImagePath:gifFilePath];
        
        if(completeBlock){
            dispatch_async(dispatch_get_main_queue(), ^{
                completeBlock(!self.error,self.error);
            });
        }
    });
    
}


- (void)createGIFfromURL:(NSURL*)videoURL loopCount:(int)loopCount startSecond:(float)fltStartSecond delayTime:(CGFloat)delayTime gifTime:(float)fltGifTime gifImagePath:(NSString *)imagePath{
    
    NSDictionary *fileProperties = [self filePropertiesWithLoopCount:loopCount];
    NSDictionary *frameProperties = [self framePropertiesWithDelayTime:delayTime];
    
    AVURLAsset *asset = [AVURLAsset assetWithURL:videoURL];
    
    float videoWidth = [[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] naturalSize].width;
    float videoHeight = [[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] naturalSize].height;
    
    GIFSize optimalSize = GIFSizeMedium;
    if (videoWidth >= 1200 || videoHeight >= 1200)
        optimalSize = GIFSizeVeryLow;
    else if (videoWidth >= 800 || videoHeight >= 800)
        optimalSize = GIFSizeLow;
    else if (videoWidth >= 400 || videoHeight >= 400)
        optimalSize = GIFSizeMedium;
    else if (videoWidth < 400|| videoHeight < 400)
        optimalSize = GIFSizeHigh;
    
    
    int frameCount = fltGifTime * kFrameInSecond;
    
    //两帧的时间间隔
    float increment = (float)fltGifTime/frameCount;
    
    // Add frames to the buffer
    NSMutableArray *timePoints = [NSMutableArray array];
    for (int currentFrame = 0; currentFrame<frameCount; ++currentFrame) {
        float seconds = fltStartSecond + (float)increment * currentFrame;
        CMTime time = CMTimeMakeWithSeconds(seconds, 1 *NSEC_PER_SEC);
        [timePoints addObject:[NSValue valueWithCMTime:time]];
    }
    
    [self createGIFforTimePoints:timePoints fromURL:videoURL fileProperties:fileProperties frameProperties:frameProperties gifImagePath:imagePath frameCount:frameCount gifSize:optimalSize];
    }


- (NSURL *)createGIFforTimePoints:(NSArray *)timePoints fromURL:(NSURL *)url fileProperties:(NSDictionary *)fileProperties  frameProperties:(NSDictionary *)frameProperties gifImagePath:(NSString *)imagePath frameCount:(int)frameCount gifSize:(GIFSize)gifSize{
    
    NSURL *fileURL = [NSURL fileURLWithPath:imagePath];
    if (fileURL == nil)
        return nil;
    
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypeGIF , frameCount, NULL);
    CGImageDestinationSetProperties(destination, (CFDictionaryRef)fileProperties);
    
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
    generator.appliesPreferredTrackTransform = YES;
    
    generator.requestedTimeToleranceBefore = kCMTimeZero;
    generator.requestedTimeToleranceAfter = kCMTimeZero;
    
    NSError *error = nil;
    CGImageRef previousImageRefCopy = nil;
    CGImageRef imageRef;
    NSLog(@"starat");
    
    
    
    for (NSValue *time in timePoints) {
        imageRef = [generator copyCGImageAtTime:[time CMTimeValue] actualTime:nil error:&error];
        if((float)gifSize/10 != 1){
            imageRef = createImageWithScale(imageRef, (float)gifSize/10);
        }
        
        if (error) {
            _error =error;
            NSLog(@"Error copying image: %@", error);
            return nil;
            
        }
        if (imageRef) {
            CGImageRelease(previousImageRefCopy);
            previousImageRefCopy = CGImageCreateCopy(imageRef);
        } else if (previousImageRefCopy) {
            imageRef = CGImageCreateCopy(previousImageRefCopy);
        } else {
            _error =[NSError errorWithDomain:NSStringFromClass([self class]) code:0 userInfo:@{NSLocalizedDescriptionKey:@"Error copying image and no previous frames to duplicate"}];
            NSLog(@"Error copying image and no previous frames to duplicate");
            return nil;
        }
        CGImageDestinationAddImage(destination, imageRef, (CFDictionaryRef)frameProperties);
        CGImageRelease(imageRef);
    }
    NSLog(@"end");
    CGImageRelease(previousImageRefCopy);
    
    // Finalize the GIF
    if (!CGImageDestinationFinalize(destination)) {
        
        _error =error;
        
        NSLog(@"Failed to finalize GIF destination: %@", error);
        if (destination != nil) {
            CFRelease(destination);
        }
        return nil;
    }
    CFRelease(destination);
    
    return fileURL;
}

#pragma mark - Helpers

CGImageRef createImageWithScale(CGImageRef imageRef, float scale) {
    
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
    CGSize newSize = CGSizeMake(CGImageGetWidth(imageRef)*scale, CGImageGetHeight(imageRef)*scale);
    CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
    
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (!context) {
        return nil;
    }
    
    // Set the quality level to use when rescaling
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);
    
    CGContextConcatCTM(context, flipVertical);
    // Draw into the context; this scales the image
    CGContextDrawImage(context, newRect, imageRef);
    
    //Release old image
    CFRelease(imageRef);
    // Get the resized image from the context and a UIImage
    imageRef = CGBitmapContextCreateImage(context);
    
    UIGraphicsEndImageContext();
#endif
    
    return imageRef;
}

#pragma mark - Properties

- (NSDictionary *)filePropertiesWithLoopCount:(int)loopCount {
    //GIF播放
    //0不循环 1无限循环
    return @{(NSString *)kCGImagePropertyGIFDictionary:
                 @{(NSString *)kCGImagePropertyGIFLoopCount: @(loopCount)}
             };
}

- (NSDictionary *)framePropertiesWithDelayTime:(float)delayTime {
    
    return @{(NSString *)kCGImagePropertyGIFDictionary:
                 @{(NSString *)kCGImagePropertyGIFDelayTime: @(delayTime)},
             (NSString *)kCGImagePropertyColorModel:(NSString *)kCGImagePropertyColorModelRGB
             };
}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,542评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,596评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,021评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,682评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,792评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,985评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,107评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,845评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,299评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,612评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,747评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,441评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,072评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,828评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,069评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,545评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,658评论 2 350

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明先生_X自主阅读 15,969评论 3 119
  • 作者:Erica Sadun,原文链接,原文日期:2016-04-08译者:zltunes;校对:numbbbbb...
    梁杰_numbbbbb阅读 319评论 0 2
  • 我心似水 淌过有你的苇丛 无心惊扰潜心修佛的你 只因你的灵静 染碧了我一身澄澈 怎的就飘到了此处? 看你呆呆吟咏 ...
    方四叶阅读 176评论 0 3
  • 只是被认为是死气沉沉之物,终日在阴暗的图书馆架子上。不幸的是,图书馆安静之极的氛围就像是举办葬礼的教堂或墓地。...
    Dawn_乾琳阅读 196评论 0 1