【短视频SDK】如何获取单视频的缩略图?
获取视频缩略图iOS和Android分别提供一个方法得到一个视频的缩略图,如果需要多张需要开发者自己调用多次即可.
1.Android获取视频缩略图,仅演示单视频缩略图获取方法
核心接口:AliyunIThumbnailFetcher
//1.创建一个AliyunIThumbnailFetcher的实例
AliyunIThumbnailFetcher mThumbnailFetcher = AliyunThumbnailFetcherFactory.createThumbnailFetcher();
//2.添加一个视频源---path为开发者视频的本地路径
mThumbnailFetcher.addVideoSource("path");
//3.设置输出参数
/*
* @param width 输出宽度
* @param height 输出高度
* @param mode 裁剪模式 (目前可以忽略,填任意值,所有的都是从中间裁剪)
* @param scaleMode 缩放模式 (目前可以忽略,填任意值,只支持裁剪模式,不支持填充模式)
* @param cacheSize 缓存大小,即缓存的缩略图数量,缓存的图片不需要重新解码取,以达到减少耗时的目的.
*/
mThumbnailFetcher.setParameters(60,60,AliyunIThumbnailFetcher.CropMode.Mediate,ScaleMode.LB, 30);
//4.获取某个时间点的缩略图
mThumbnailFetcher.requestThumbnailImage(times,
new AliyunIThumbnailFetcher.OnThumbnailCompletion() {
public void onThumbnailReady(ShareableBitmap frameBitmap, long time){
//成功拿到图片的回调frameBitmap.getData()即可拿到一个bitmap
//需要拿到多张如何做?就在onThumbnailReady这个回调里面再调用一 次requestThumbnailImage传入不一样的时间即可.
}
public void onError(int errorCode) {
//出错的回调
}
});
//5.释放
mThumbnailFetcher.release()
注意:目前仅专业版有该接口.如基础版或者是标准版有该需求可以通过MediaMetadataRetriever来获取,单该接口仅能返回关键帧的图片,如果需要获取N张会有重复图片的情况.可耐心等待SDK提供独立的获取缩略图的接口.
public Bitmap getVideoThumbnail(String filePath) { Bitmap bitmap = null; MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { retriever.setDataSource(filePath); bitmap = retriever.getFrameAtTime(); } catch(IllegalArgumentException e) { e.printStackTrace(); } catch (RuntimeException e) { e.printStackTrace(); } finally { try { retriever.release(); } catch (RuntimeException e) { e.printStackTrace(); } } return bitmap; }
2.iOS获取视频缩略图,仅演示单视频缩略图获取方法
iOS因为系统函数就可以直接做到获取非关键帧缩略图,所以我们直接使用AVFoundation获取即可.需要多张图片调用多次即可.
/** * 获取视频的缩略图方法 * * @param filePath 视频的本地路径 * * @return 视频截图 */ - (UIImage *)getScreenShotImageFromVideoPath:(NSString *)filePath{ UIImage *shotImage; //视频路径URL NSURL *fileURL = [NSURL fileURLWithPath:filePath]; AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:fileURL options:nil]; AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset]; gen.appliesPreferredTrackTransform = YES; CMTime time = CMTimeMakeWithSeconds(0.0, 600); NSError *error = nil; CMTime actualTime; CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error]; shotImage = [[UIImage alloc] initWithCGImage:image]; CGImageRelease(image); return shotImage; }
最后更新:2017-08-29 20:32:18