iOS 在线视频生成GIF图功能的方法

2020-01-21 04:47:07王旭

第二步:本地视频生成GIF图


/**
 生成GIF图片
 @param videoURL 视频的路径URL
 @param loopCount 播放次数
 @param time 每帧的时间间隔 默认0.25s
 @param imagePath 存放GIF图片的文件路径
 @param completeBlock 完成的回调

 */
 #pragma mark--制作GIF
- (void)createGIFfromURL:(NSURL*)videoURL loopCount:(int)loopCount delayTime:(CGFloat )time gifImagePath:(NSString *)imagePath complete:(CompleteBlock)completeBlock {
 
  _completeBlock =completeBlock;
 

 float delayTime = time?:0.25;
 
 // Create properties dictionaries
 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;
 
 // Get the length of the video in seconds
 float videoLength = (float)asset.duration.value/asset.duration.timescale;
 int framesPerSecond = 4;
 int frameCount = videoLength*framesPerSecond;
 
 // How far along the video track we want to move, in seconds.
 float increment = (float)videoLength/frameCount;
 
 // Add frames to the buffer
 NSMutableArray *timePoints = [NSMutableArray array];
 for (int currentFrame = 0; currentFrame<frameCount; ++currentFrame) {
  float seconds = (float)increment * currentFrame;
  CMTime time = CMTimeMakeWithSeconds(seconds, [timeInterval intValue]);
  [timePoints addObject:[NSValue valueWithCMTime:time]];
 }
 
 
 //completion block
 NSURL *gifURL = [self createGIFforTimePoints:timePoints fromURL:videoURL fileProperties:fileProperties frameProperties:frameProperties gifImagePath:imagePath frameCount:frameCount gifSize:_gifSize?:GIFSizeMedium];
 
 if (_completeBlock) {
  
  // Return GIF URL
  _completeBlock(_error,gifURL);
 }

}

经过上面两步,就可以生成本地的视频和GIF图了,存储在沙盒即可。贴上两步所用到的方法:


#pragma mark - Base methods

- (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;
 
 CMTime tol = CMTimeMakeWithSeconds([tolerance floatValue], [timeInterval intValue]);
 generator.requestedTimeToleranceBefore = tol;
 generator.requestedTimeToleranceAfter = tol;
 
 NSError *error = nil;
 CGImageRef previousImageRefCopy = nil;
 for (NSValue *time in timePoints) {
  CGImageRef imageRef;
  
  #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
   imageRef = (float)gifSize/10 != 1 ? createImageWithScale([generator copyCGImageAtTime:[time CMTimeValue] actualTime:nil error:&error], (float)gifSize/10) : [generator copyCGImageAtTime:[time CMTimeValue] actualTime:nil error:&error];
  #elif TARGET_OS_MAC
   imageRef = [generator copyCGImageAtTime:[time CMTimeValue] actualTime:nil error:&error];
  #endif
  
  if (error) {
   
   _error =error;
   logdebug(@"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"}];
   logdebug(@"Error copying image and no previous frames to duplicate");
   return nil;
  }
  CGImageDestinationAddImage(destination, imageRef, (CFDictionaryRef)frameProperties);
  CGImageRelease(imageRef);
 }
 CGImageRelease(previousImageRefCopy);
 
 // Finalize the GIF
 if (!CGImageDestinationFinalize(destination)) {
  
  _error =error;
  
  logdebug(@"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 {
 return @{(NSString *)kCGImagePropertyGIFDictionary:
    @{(NSString *)kCGImagePropertyGIFLoopCount: @(loopCount)}
    };
}

- (NSDictionary *)framePropertiesWithDelayTime:(float)delayTime {

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