ios 从 iPhone SDK 中的视频 url 创建缩略图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7501413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create thumbnail from a video url in IPhone SDK
提问by TheRock
I am trying to acquire a thumbnail from a video url. The video is a stream (HLS) with the m3u8 format. I've already tried requestThumbnailImagesAtTimes from the MPMoviePlayerController, but that didn't work. Does anyone have a solution for that problem? If so how'd you do it?
我正在尝试从视频网址获取缩略图。视频是 m3u8 格式的流 (HLS)。我已经尝试过 MPMoviePlayerController 中的 requestThumbnailImagesAtTimes,但这没有用。有没有人有解决这个问题的方法?如果是,你是怎么做的?
回答by Aaron Brager
If you don't want to use MPMoviePlayerController
, you can do this:
如果你不想使用MPMoviePlayerController
,你可以这样做:
AVAsset *asset = [AVAsset assetWithURL:sourceURL];
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
CMTime time = CMTimeMake(1, 1);
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef); // CGImageRef won't be released by ARC
Here's an example in Swift:
这是 Swift 中的一个示例:
func thumbnail(sourceURL sourceURL:NSURL) -> UIImage {
let asset = AVAsset(URL: sourceURL)
let imageGenerator = AVAssetImageGenerator(asset: asset)
let time = CMTime(seconds: 1, preferredTimescale: 1)
do {
let imageRef = try imageGenerator.copyCGImageAtTime(time, actualTime: nil)
return UIImage(CGImage: imageRef)
} catch {
print(error)
return UIImage(named: "some generic thumbnail")!
}
}
I prefer using AVAssetImageGenerator
over MPMoviePlayerController
because it is thread-safe, and you can have more than one instantiated at a time.
我更喜欢使用AVAssetImageGenerator
overMPMoviePlayerController
因为它是线程安全的,并且一次可以实例化多个。
回答by Faizan Refai
Acquire a thumbnail from a video url.
从视频网址获取缩略图。
NSString *strVideoURL = @"http://www.xyzvideourl.com/samplevideourl";
NSURL *videoURL = [NSURL URLWithString:strVideoURL] ;
MPMoviePlayerController *player = [[[MPMoviePlayerController alloc] initWithContentURL:videoURL]autorelease];
UIImage *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
player = nil;
Replace your video URL string with strVideoURL
.
You will get thumbnail as a output from video
.
And thumbnail is UIImage
type data !
将您的视频 URL 字符串替换为strVideoURL
. 您将获得缩略图作为video
. 缩略图是UIImage
类型数据!
回答by Ankit Goyal
-(UIImage *)loadThumbNail:(NSURL *)urlVideo
{
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:urlVideo options:nil];
AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generate.appliesPreferredTrackTransform=TRUE;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 60);
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err];
NSLog(@"err==%@, imageRef==%@", err, imgRef);
return [[UIImage alloc] initWithCGImage:imgRef];
}
Add AVFoundation
framework in your project and don't forget to import <AVFoundation/AVFoundation.h>
and you have to pass the path of your video saved in document directory as a parameter and receive the image as UIImage
.
AVFoundation
在您的项目中添加框架,不要忘记导入<AVFoundation/AVFoundation.h>
,您必须将保存在文档目录中的视频路径作为参数传递,并以 .png 格式接收图像UIImage
。
回答by D-eptdeveloper
you can get the thumbnail from your video url with the use of below code
您可以使用以下代码从您的视频网址获取缩略图
MPMoviePlayerController *player = [[[MPMoviePlayerController alloc] initWithContentURL:videoURL]autorelease];
UIImage *thumbnail = [player thumbnailImageAtTime:0.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
回答by Prine
Maybe this is useful for someone else who faces the same problem. I needed an easy solution for creating a thumbnail for Images, PDFs and Videos. To solve that problem I've created the following Library (in Swift).
也许这对面临同样问题的其他人有用。我需要一个简单的解决方案来为图像、PDF 和视频创建缩略图。为了解决这个问题,我创建了以下库(在 Swift 中)。
https://github.com/prine/ROThumbnailGenerator
https://github.com/prine/ROThumbnailGenerator
The usage is very straightforward: var thumbnailImage = ROThumbnail.getThumbnail(url)
用法很简单:varthumbnailImage = ROThumbnail.getThumbnail(url)
It has internally three different implementations and depending on the file extension it does create the thumbnail. You can easily add your own implementation if you need a thumbnail creator for another file extension.
它在内部具有三种不同的实现,并根据文件扩展名创建缩略图。如果您需要另一个文件扩展名的缩略图创建者,您可以轻松添加自己的实现。
回答by Ankit Kumar Gupta
Swift 3 Version :
斯威夫特 3 版本:
func createThumbnailOfVideoFromFileURL(videoURL: String) -> UIImage? {
let asset = AVAsset(url: URL(string: videoURL)!)
let assetImgGenerate = AVAssetImageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
let time = CMTimeMakeWithSeconds(Float64(1), 100)
do {
let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
let thumbnail = UIImage(cgImage: img)
return thumbnail
} catch {
// Set a default image if Image is not acquired
return UIImage(named: "ico_placeholder")
}
}
回答by Disha
For Swift 3.0:
对于 Swift 3.0:
func generateThumbnailForVideoAtURL(filePathLocal: NSString) -> UIImage? {
let vidURL = NSURL(fileURLWithPath:filePathLocal as String)
let asset = AVURLAsset(url: vidURL as URL)
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true
let timestamp = CMTime(seconds: 1, preferredTimescale: 60)
do {
let imageRef = try generator.copyCGImage(at: timestamp, actualTime: nil)
let frameImg : UIImage = UIImage(cgImage: imageRef)
return frameImg
} catch let error as NSError {
print("Image generation failed with error ::\(error)")
return nil
}
}
回答by N?Bi Mac
For Swift 5you can get it this way:
对于Swift 5,您可以通过以下方式获得:
First import AVKit or AVFoundation
to ViewController
首先import AVKit or AVFoundation
要ViewController
import AVKit
Code:
代码:
// Get Thumbnail Image from URL
private func getThumbnailFromUrl(_ url: String?, _ completion: @escaping ((_ image: UIImage?)->Void)) {
guard let url = URL(string: url ?? "") else { return }
DispatchQueue.main.async {
let asset = AVAsset(url: url)
let assetImgGenerate = AVAssetImageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
let time = CMTimeMake(value: 2, timescale: 1)
do {
let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
let thumbnail = UIImage(cgImage: img)
completion(thumbnail)
} catch {
print("Error :: ", error.localizedDescription)
completion(nil)
}
}
}
Usage
用法
@IBOutlet weak imgThumbnail: ImageView!
and then call getThumbnailFromUrl
method and pass URL
as a Sting
然后调用getThumbnailFromUrl
方法并URL
作为Sting
self.getThumbnailFromUrl(videoURL) { [weak self] (img) in
guard let `self` = self else { return }
if let img = img {
self.imgThumbnail.image = img
}
}
Thank you
谢谢
回答by Avt
Swift 2 code with AVAssetImageGenerator:
带有 AVAssetImageGenerator 的 Swift 2 代码:
func thumbnailImageForVideo(url:NSURL) -> UIImage?
{
let asset = AVAsset(URL: url)
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true
var time = asset.duration
//If possible - take not the first frame (it could be completely black or white on camara's videos)
time.value = min(time.value, 2)
do {
let imageRef = try imageGenerator.copyCGImageAtTime(time, actualTime: nil)
return UIImage(CGImage: imageRef)
}
catch let error as NSError
{
print("Image generation failed with error \(error)")
return nil
}
}