iOS 原生api视频转Gif

Google了很久,没查到,没办法自己写吧

+ (void)createGifWithVideo:(NSString *)inputPath outPutPath:(NSString *)outputPath sampleInterval:(NSUInteger)sampleInterval callback:(void (^ _Nonnull)(float, BOOL))callback
{
    if ([[NSFileManager defaultManager] fileExistsAtPath:outputPath])
    {
        [[NSFileManager defaultManager] removeItemAtPath:outputPath error:NULL];
    }
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:inputPath] options:nil];
    int64_t value = asset.duration.value;
    int64_t scale = asset.duration.timescale;
    NSInteger totalFrames = (value/scale) * 1000/sampleInterval;//总帧数
    
    AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    generator.appliesPreferredTrackTransform = YES;
    //下面两个值设为0表示精确取帧,否则系统会有优化取出来的帧时间间隔不对等
    generator.requestedTimeToleranceAfter = kCMTimeZero;
    generator.requestedTimeToleranceBefore = kCMTimeZero;
    
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL((CFURLRef)[NSURL fileURLWithPath:outputPath], kUTTypeGIF, totalFrames, NULL);
    NSDictionary *frameProperties = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.3f] forKey:(NSString *)kCGImagePropertyGIFDelayTime] forKey:(NSString *)kCGImagePropertyGIFDictionary];
    NSDictionary *gifProperties = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:1] forKey:(NSString *)kCGImagePropertyGIFLoopCount]forKey:(NSString *)kCGImagePropertyGIFDictionary];
    CGImageDestinationSetProperties(destination, (CFDictionaryRef)gifProperties);
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (int i = 0; i < totalFrames; i++)
        {
            CMTime time = CMTimeMakeWithSeconds(sampleInterval * 0.001 * i, (int)scale);//sampleInterval单位是毫秒,而CMTimeMakeWithSeconds第一个参数时间戳是秒
            NSError *error = nil;
            CMTime actualTime;
            CGImageRef image = [generator copyCGImageAtTime:time actualTime:&actualTime error:&error];
            
            CGImageDestinationAddImage(destination, image, (CFDictionaryRef)frameProperties);
            CGImageRelease(image);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (callback)
                {
                    callback((i+1) * 1.0/totalFrames, NO);
                }
            });
        }
        
        CGImageDestinationFinalize(destination);
        CFRelease(destination);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (callback)
            {
                callback(1.0, YES);
            }
        });
    });
}

你可能感兴趣的:(iOS 原生api视频转Gif)