- videoURL:视频本地路径
- gifOutputPath:生成的GIF存储路径
- (NSURL *)gifThumbnailURLFromVideo:(NSURL *)videoURL gifOutputPath:(NSString *)gifOutputPath
{
CGFloat increment = 0.1;
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
float movieLength = (float)asset.duration.value /asset.duration.timescale;
int frameCount = movieLength / increment;
float tolerance = 0.01f;
CFURLRef gifOutputURL = (__bridge CFURLRef) [NSURL fileURLWithPath:gifOutputPath];
CGImageDestinationRef destination = CGImageDestinationCreateWithURL(gifOutputURL, kUTTypeGIF, frameCount >= 24 ? 10 : frameCount,nil);
generator.requestedTimeToleranceBefore = CMTimeMakeWithSeconds(tolerance, 600) ;
generator.requestedTimeToleranceAfter = CMTimeMakeWithSeconds(tolerance, 600);
generator.appliesPreferredTrackTransform = YES;
NSDictionary *frameProperties = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:increment]
forKey:(NSString *)kCGImagePropertyGIFDelayTime]
forKey:(NSString *)kCGImagePropertyGIFDictionary];
NSDictionary *gifProperties = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:0]
forKey:(NSString *)kCGImagePropertyGIFLoopCount]
forKey:(NSString *)kCGImagePropertyGIFDictionary];
CGImageDestinationSetProperties(destination, (CFDictionaryRef)gifProperties);
CGSize videoSize = [[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] naturalSize];
float imageWidth = 200.0f;
generator.maximumSize = CGSizeMake( imageWidth , imageWidth/videoSize.width * videoSize.height);
NSError *error = nil;
for (int i = 0 ; i <= 20; ) {
CMTime imageTime = CMTimeMakeWithSeconds(i*increment, 600);
CGImageRef image = [generator copyCGImageAtTime:imageTime actualTime:nil error:&error];
if (error) {
return nil;
}
CGImageDestinationAddImage(destination, image, (CFDictionaryRef)frameProperties);
CFRelease(image);
i += 4;
}
//Inverse
for (int i = 16 ; i >= 4; ) {
CMTime imageTime = CMTimeMakeWithSeconds(i*increment, 600);
CGImageRef image = [generator copyCGImageAtTime:imageTime actualTime:nil error:&error];
if (error) {
return nil;
}
CGImageDestinationAddImage(destination, image, (CFDictionaryRef)frameProperties);
CFRelease(image);
i -= 4;
}
CGImageDestinationFinalize(destination);
CFRelease(destination);
return [NSURL fileURLWithPath:gifOutputPath];
}