視頻轉GIF的實現

/**
 *  視頻轉GIF
 *  @param videoURL videoURL
 *  @param beginSecond 錄制開始時間
 *  @param durationSecond 錄制持續時間
 *  @param successBlock 成功
 */
+ (void)thumbnailImageForVideo:(NSURL *)videoURL begin:(int)beginSecond Duration:(int)durationSecond responseSuccess:(void (^)(NSArray *resultArr))successBlock{
NSMutableArray *imgArr = [[NSMutableArray alloc] init];
AVAsset *myAsset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
NSParameterAssert(myAsset);


CMTime cmtime = myAsset.duration; //視頻時間信息結構體
CMTimeScale fps = 10;//生成gif的幀率 視頻幀率myAsset.duration.timescale  fps
Float64 durationSeconds = CMTimeGetSeconds(cmtime); //視頻總秒數
NSMutableArray *times = [NSMutableArray array];

float count = durationSecond*fps;
for (int i = 0; i < count ; i++) {
    CMTime timeFrame = CMTimeMake(beginSecond*fps+i, fps); //第i幀 幀率
    NSValue *timeValue = [NSValue valueWithCMTime:timeFrame];
    [times addObject:timeValue];
}

AVAssetImageGenerator *imgGenerator = [[AVAssetImageGenerator alloc] initWithAsset:myAsset]; //防止時間出現偏差
imgGenerator.requestedTimeToleranceBefore = kCMTimeZero;
imgGenerator.requestedTimeToleranceAfter = kCMTimeZero;

[imgGenerator generateCGImagesAsynchronouslyForTimes:times completionHandler:^(CMTime requestedTime, CGImageRef _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
     if (image){
         [CATransaction begin];
         [CATransaction setDisableActions:YES];
         UIImage *img = [UIImage imageWithCGImage:image];
         [imgArr addObject:img];
         [CATransaction commit];
     }
     if (result == AVAssetImageGeneratorSucceeded) {
         // Do something interesting with the image.
         if (imgArr.count==times.count) {
             [self makeGifImgViewAction:imgArr fps:1/fps];
             successBlock(imgArr);
             return ;
         }
     }
    
     if (result == AVAssetImageGeneratorFailed) {
         DDLogDebug(@"Failed with error: %@", [error localizedDescription]);
     }
     if (result == AVAssetImageGeneratorCancelled) {
         DDLogDebug(@"Canceled");
     }
 }];

}

// 生成gif圖片
+(void)makeGifImgViewAction:(NSArray*)imageArr fps:(float)fps{
 //gif的制作
//圖像目標
CGImageDestinationRef destination;

//創建輸出路徑
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"];


DDLogDebug(@"%@",path);

//創建CFURL對象
/*
 CFURLCreateWithFileSystemPath(CFAllocatorRef allocator, CFStringRef filePath, CFURLPathStyle pathStyle, Boolean isDirectory)
 
 allocator : 分配器,通常使用kCFAllocatorDefault
 filePath : 路徑
 pathStyle : 路徑風格,我們就填寫kCFURLPOSIXPathStyle 更多請打問號自己進去幫助看
 isDirectory : 一個布爾值,用于指定是否filePath被當作一個目錄路徑解決時相對路徑組件
 */
CFURLRef url = CFURLCreateWithFileSystemPath (
                                              kCFAllocatorDefault,
                                              (CFStringRef)path,
                                              kCFURLPOSIXPathStyle,
                                              false);

//通過一個url返回圖像目標 kUTTypeGIF  CFStringRef

destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, imageArr.count, NULL);

//設置gif的信息,播放間隔時間,基本數據,和delay時間
NSDictionary *frameProperties = [NSDictionary
                                 dictionaryWithObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                                       [NSNumber numberWithFloat:fps],
                                                       (NSString *)kCGImagePropertyGIFDelayTime,
                                                       nil]
                                 forKey:(NSString *)kCGImagePropertyGIFDictionary];

//設置gif信息
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];
//合成gif
for (UIImage* dImg in imageArr)
{
    CGImageDestinationAddImage(destination, dImg.CGImage, (__bridge CFDictionaryRef)frameProperties);
}
CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)gifProperties);
CGImageDestinationFinalize(destination);
CFRelease(destination);


DDLogDebug(@"animated GIF file created at %@", path);

NSData *data = [NSData dataWithContentsOfFile:path];
NSDictionary *metadata = @{@"UTI":(__bridge NSString *)kUTTypeGIF};
// 保存到本地相冊
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageDataToSavedPhotosAlbum:data metadata:metadata completionBlock:^(NSURL *assetURL, NSError *error) {
    
    if (error) {
        DDLogDebug(@"寫數據失敗:%@",error);
    }else{
        
        [library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
            DDLogDebug(@"成功保存到相冊");
        } failureBlock:^(NSError *error) {
            DDLogDebug(@"gif保存到的ALAsset有問題, URL:%@,err:%@",assetURL,error);
        }];
    }
}] ;

}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容