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

在一些视频APP中,都可以看到一个将在线视频转成GIF图的功能。下面就来说说思路以及实现。我们知道本地视频可以生成GIF,那么将在线视频截取成本地视频不就可以了吗?经过比较,腾讯视频App也是这么做的。话不多说,下面开始上代码:

第一步:截取视频

#pragma mark -截取视频
- (void)interceptVideoAndVideoUrl:(NSURL *)videoUrl withOutPath:(NSString *)outPath outputFileType:(NSString *)outputFileType range:(NSRange)videoRange intercept:(InterceptBlock)interceptBlock {

 _interceptBlock =interceptBlock;

 //不添加背景音乐
 NSURL *audioUrl =nil;
 //AVURLAsset此类主要用于获取媒体信息,包括视频、声音等
 AVURLAsset* audioAsset = [[AVURLAsset alloc] initWithURL:audioUrl options:nil];
 AVURLAsset* videoAsset = [[AVURLAsset alloc] initWithURL:videoUrl options:nil];

 //创建AVMutableComposition对象来添加视频音频资源的AVMutableCompositionTrack
 AVMutableComposition* mixComposition = [AVMutableComposition composition];

 //CMTimeRangeMake(start, duration),start起始时间,duration时长,都是CMTime类型
 //CMTimeMake(int64_t value, int32_t timescale),返回CMTime,value视频的一个总帧数,timescale是指每秒视频播放的帧数,视频播放速率,(value / timescale)才是视频实际的秒数时长,timescale一般情况下不改变,截取视频长度通过改变value的值
 //CMTimeMakeWithSeconds(Float64 seconds, int32_t preferredTimeScale),返回CMTime,seconds截取时长(单位秒),preferredTimeScale每秒帧数

 //开始位置startTime
 CMTime startTime = CMTimeMakeWithSeconds(videoRange.location, videoAsset.duration.timescale);
 //截取长度videoDuration
 CMTime videoDuration = CMTimeMakeWithSeconds(videoRange.length, videoAsset.duration.timescale);

 CMTimeRange videoTimeRange = CMTimeRangeMake(startTime, videoDuration);

 //视频采集compositionVideoTrack
 AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];

 // 避免数组越界 tracksWithMediaType 找不到对应的文件时候返回空数组
 //TimeRange截取的范围长度
 //ofTrack来源
 //atTime插放在视频的时间位置
 [compositionVideoTrack insertTimeRange:videoTimeRange ofTrack:([videoAsset tracksWithMediaType:AVMediaTypeVideo].count>0) ? [videoAsset tracksWithMediaType:AVMediaTypeVideo].firstObject : nil atTime:kCMTimeZero error:nil];

 //视频声音采集(也可不执行这段代码不采集视频音轨,合并后的视频文件将没有视频原来的声音)

 AVMutableCompositionTrack *compositionVoiceTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

 [compositionVoiceTrack insertTimeRange:videoTimeRange ofTrack:([videoAsset tracksWithMediaType:AVMediaTypeAudio].count>0)?[videoAsset tracksWithMediaType:AVMediaTypeAudio].firstObject:nil atTime:kCMTimeZero error:nil];

 //声音长度截取范围==视频长度
 CMTimeRange audioTimeRange = CMTimeRangeMake(kCMTimeZero, videoDuration);

 //音频采集compositionCommentaryTrack
 AVMutableCompositionTrack *compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

 [compositionAudioTrack insertTimeRange:audioTimeRange ofTrack:([audioAsset tracksWithMediaType:AVMediaTypeAudio].count > 0) ? [audioAsset tracksWithMediaType:AVMediaTypeAudio].firstObject : nil atTime:kCMTimeZero error:nil];

 //AVAssetExportSession用于合并文件,导出合并后文件,presetName文件的输出类型
 AVAssetExportSession *assetExportSession = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetPassthrough];

 //混合后的视频输出路径
 NSURL *outPutURL = [NSURL fileURLWithPath:outPath];

 if ([[NSFileManager defaultManager] fileExistsAtPath:outPath])
 {
  [[NSFileManager defaultManager] removeItemAtPath:outPath error:nil];
 }

 //输出视频格式
 assetExportSession.outputFileType = outputFileType;
 assetExportSession.outputURL = outPutURL;
 //输出文件是否网络优化
 assetExportSession.shouldOptimizeForNetworkUse = YES;
 [assetExportSession exportAsynchronouslyWithCompletionHandler:^{

  dispatch_async(dispatch_get_main_queue(), ^{

   switch (assetExportSession.status) {
    case AVAssetExportSessionStatusFailed:

     if (_interceptBlock) {

      _interceptBlock(assetExportSession.error,outPutURL);
     }

     break;

    case AVAssetExportSessionStatusCancelled:{

     logdebug(@"Export Status: Cancell");

     break;
    }
    case AVAssetExportSessionStatusCompleted: {

     if (_interceptBlock) {

      _interceptBlock(nil,outPutURL);
     }

     break;
    }
    case AVAssetExportSessionStatusUnknown: {

     logdebug(@"Export Status: Unknown");
    }
    case AVAssetExportSessionStatusExporting : {

     logdebug(@"Export Status: Exporting");
    }
    case AVAssetExportSessionStatusWaiting: {

     logdebug(@"Export Status: Wating");
    }

   }

  });

 }];
}

第二步:本地视频生成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
   };
}

最后,截取的本地视频可用AVPlayer播放,生成的GIF图则用UIWebView或者WKWebView又或者 YYImage 加载即可。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • iOS开发中实现显示gif图片的方法

    我们知道Gif是由一阵阵画面组成的,而且每一帧画面播放的时常可能会不相等,观察上面两个例子,发现他们都没有对Gif中每一帧的显示时常做处理,这样的结果就是整个Gif中每一帧画面都是以固定的速度向前播放,很显然这并不总会符合需求.   于是自己写一个解析Gif的工具类,解决每一帧画面并遵循每一帧所对应的显示时间进行播放.   程序的思路如下:   1.首先使用ImageIO库中的CGImageSource家在Gif文件.   2.通过CGImageSource获取到Gif文件中的总的帧数,以及每一

  • iOS Gif图片展示N种方式(原生+第三方)

    本文分享了iOS Gif图片展示N种方式,供大家参考,具体内容如下 原生方法: 1.UIWebView 特点:加载速度略长,性能更优,播放的gif动态图更加流畅. //动态展示GIF图片-WebView -(void)showGifImageWithWebView{ //读取gif图片数据 NSData *gifData = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"earthGif"

  • iOS之加载Gif图片的方法

    Gif图片是非常常见的图片格式,尤其是在聊天的过程中,Gif表情使用地很频繁.但是iOS竟然没有现成的支持加载和播放Gif的类. 简单地汇总了一下,大概有以下几种方法: 一.加载本地Gif文件 1.使用UIWebView // 读取gif图片数据 UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,200,200)]; [self.view addSubview:webView]; NSString *path

  • iOS中gif图的显示方法示例

    一.前言 iOS开发中,大部分时候我们显示一张静态图就可以了,但是有的时候为了UI表现更生动,我就有可能需要展示gif图来达到效果了. 网上找了一下,显示gif图的框架找到了两个. SDWebImage YYImage 二.显示本地gif图 SDWebImage和YYImage的显示本地图片代码. //load loacle gif image - (void)loadLocaleGifImage{ //sdwebimage [self labelFactoryWithFrame:CGRectM

  • 浅析IOS中播放gif动态图的方法

    一.引言 在iOS开发中,UIImageView类专门来负责图片数据的渲染,并且UIImageView也有帧动画的方法来播放一组图片,但是对于gif类型的数据,UIImageView中并没有现成的接口提供给开发者使用,在iOS中一般可以通过两种方式来播放gif动态图,一种方式是通过ImageIO框架中的方法将gif文件中的数据进行解析,再使用coreAnimation核心动画来播放gif动画,另一种方式计较简单,可以直接通过webView来渲染gif图. 二.为原生的UIImageView添加类

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

    在一些视频APP中,都可以看到一个将在线视频转成GIF图的功能.下面就来说说思路以及实现.我们知道本地视频可以生成GIF,那么将在线视频截取成本地视频不就可以了吗?经过比较,腾讯视频App也是这么做的.话不多说,下面开始上代码: 第一步:截取视频 #pragma mark -截取视频 - (void)interceptVideoAndVideoUrl:(NSURL *)videoUrl withOutPath:(NSString *)outPath outputFileType:(NSStrin

  • jQuery轮播图功能制作方法详解

    本文实例讲述了jQuery轮播图功能制作方法.分享给大家供大家参考,具体如下: 在写轮播图之前我们先看看这个轮播图完成后的样式是怎样的 素材图片 : 代码 HTML代码 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-w

  • jQuery轮播图功能实现方法

    本文实例为大家分享了jQuery轮播图功能的实现代码,供大家参考,具体内容如下 jQuery轮播(无animation) html布局 <!-- 整个轮播区域 --> <div class="container"> <!-- 轮播图 --> <ul class="items" style="left:-200px"> <!-- 实际上只轮播5张图,将实际上的第一张放在最后一张,实际上的最后一张

  • C#使用iTextSharp设置PDF所有页面背景图功能实例

    本文实例讲述了C#使用iTextSharp设置PDF所有页面背景图功能的方法.分享给大家供大家参考.具体如下: 在生成PDF 的时候,虽然可以在页面中设置背景图. 但有些内容过长夸页面的时候,就很难设置背景图,变成了空白背景的页面! 以下是重新生成每一页 PDF 背景图功能代码! public void SetPdfBackground(string pdfFilePath) { //重新生成的 PDF 的路径 string destFile = HttpContext.Current.Serv

  • JavaScript实现自动生成网页元素功能(按钮、文本等)

    创建元素的方法: 1.利用createTextNode()创建一个文本对象 2.利用createElement()创建一个标签对象 3.直接利用容器标签中的一个属性:innerHTML-----本质上改该标签容器中的"html代码",不是我们认为的对象树的操作 详解代码: <body> <input type="button" value="创建并添加节点1" onclick="addNode1()"/>

  • Android 破解视频App去除广告功能详解及解决办法总结

    Android 破解视频App去除广告功能 作为一个屌丝程序猿也有追剧的时候,但是当打开视频app的时候,那些超长的广告已经让我这个屌丝无法忍受了,作为一个程序猿看视频还要出现广告那就是打我脸,但是我有没有钱买会员,只能靠着毕生技能去耍耍去除广告了.下面就来介绍一下如何进行视频广告的去除. 一.视频广告播放原理 首先我们需要了解的一个基本知识点那就是广告其实也是一段视频,那么他肯定有请求地址和播放地址.那么我们的思路就来了,如果能够得到这些地址的话,我们就可以去除广告了,为什么呢?因为我们知道所

  • iOS应用开发中矢量图的使用及修改矢量图颜色的方法

    之前捣鼓了点东西,要适配6和Plus,自己做做切图才发现确实有够烦.基于矢量图生成PNG图形的方法也是事后才知道,学习下,希望接下来可以实践.下面进入译文. iOS应用的视觉形式通常是以图形元素驱动的.在设计开发一款应用时,你需要不同规格的应用图标,例如不同尺寸的Default.png图片,同时还需要为UI的实现准备@1x和@2x图形资源.所有这些图形元素都会让你的产品看上去更吸引人,但弊端也是很明显的 - 你需要为每种规格的图形元素单独切图.而随着iPhone 6及Plus的发布,我们又多了一

  • 下载在线视频的方法集合

    现在在线视频越来越多了,想下载怎么办?下面我总结了三条方法,好好学习哦.恩.主要是针对FLV视频的,什么是FLV视频?就是土豆网,六间房,56,mofile,youtube等视频网站播放的流媒体.其他的诸如WMV,MPG等格式,我就稍微讲下. 如果是WMP视频,右击视频--属性,即可看到真实视频地址.如果是Real视频,右击视频--用Real Player播放,然后在本地打开的那个realplayer中,依次选择文件→剪辑信息→编辑剪辑属性,即可看到真实地址了. 第一种:利用临时文件夹 这种方法

  • java使用ffmpeg实现上传视频的转码提取视频的截图等功能(代码操作)

    ffmpeg视频采集功能非常强大,不仅可以采集视频采集卡或USB摄像头的图像,还可以进行屏幕录制,同时还支持以RTP方式将视频流传送给支持RTSP的流媒体服务器,支持直播应用.ffmpeg能解析的格式和不能解析的格式都一一给大家说明了,具体内容详情跟随一起看看吧, 1.能支持的格式 ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等) 2.不能支持的格式 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等),可以先用别的工具(menco

随机推荐