从 iOS 中的视频 url 或数据获取缩略图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1347562/
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
Getting a thumbnail from a video url or data in iOS
提问by Daniel
I am trying to acquire a thumbnail (of the first frame) from a video taken from iphone 3GS camera so I can display it. How to do this?
我正在尝试从 iphone 3GS 相机拍摄的视频中获取缩略图(第一帧的),以便我可以显示它。这该怎么做?
回答by Diken Shah
-(UIImage *)generateThumbImage : (NSString *)filepath
{
NSURL *url = [NSURL fileURLWithPath:filepath];
AVAsset *asset = [AVAsset assetWithURL:url];
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
imageGenerator.appliesPreferredTrackTransform = YES;
CMTime time = [asset duration];
time.value = 0;
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef); // CGImageRef won't be released by ARC
return thumbnail;
}
you can get the frame using the time.value suppose you want to 1 second frame then use the
您可以使用 time.value 获取帧,假设您想要 1 秒帧,然后使用
time.value = 1000 //Time in milliseconds
回答by Daniel
The answer to this question is that one can now with 4.0 iOS get thumbnails using AVFoundation, the following code where the class property url is the movie url, will do the trick (you can get the thumbnail at any time, in the example its at time 0)
这个问题的答案是现在可以使用 4.0 iOS 使用 AVFoundation 获取缩略图,下面的代码,其中类属性 url 是电影 url,可以解决问题(您可以随时获取缩略图,在示例中它位于时间 0)
-(void)generateImage
{
AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:self.url options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform=TRUE;
[asset release];
CMTime thumbTime = CMTimeMakeWithSeconds(0,30);
AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
if (result != AVAssetImageGeneratorSucceeded) {
NSLog(@"couldn't generate thumbnail, error:%@", error);
}
[button setImage:[UIImage imageWithCGImage:im] forState:UIControlStateNormal];
thumbImg=[[UIImage imageWithCGImage:im] retain];
[generator release];
};
CGSize maxSize = CGSizeMake(320, 180);
generator.maximumSize = maxSize;
[generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler];
}
回答by Bushra Shahid
NSURL *videoURL = [NSURL fileURLWithPath:url];
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
UIImage *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
//Player autoplays audio on init
[player stop];
[player release];
Check this link for an alternative: thumbnailImageAtTime: now deprecated - What's the alternative?
检查此链接以获取替代方法: thumbnailImageAtTime:现在已弃用 - 替代方法是什么?
回答by E-Madd
Best method I've found... MPMoviePlayerController thumbnailImageAtTime:timeOption
我找到的最好的方法... MPMoviePlayerController thumbnailImageAtTime:timeOption
回答by Dharmbir Singh
SWIFT 2.0
斯威夫特 2.0
You can generate in swift in two ways 1. AVFoundation 2. MPMoviePlayerController
您可以通过两种方式快速生成 1. AVFoundation 2. MPMoviePlayerController
1.
func generateThumnail(url : NSURL) -> UIImage{
var asset : AVAsset = AVAsset.assetWithURL(url) as AVAsset
var assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
var error : NSError? = nil
var time : CMTime = CMTimeMake(1, 30)
var img : CGImageRef = assetImgGenerate.copyCGImageAtTime(time, actualTime: nil, error: &error)
var frameImg : UIImage = UIImage(CGImage: img)!
return frameImg
}
2.
override func viewDidLoad() {
super.viewDidLoad()
var moviePlayer : MPMoviePlayerController! = MPMoviePlayerController(contentURL: moviePlayManager.movieURL)
moviePlayer.view.frame = CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width:
self.view.frame.size.width, height: self.view.frame.height)
moviePlayer.fullscreen = true
moviePlayer.controlStyle = MPMovieControlStyle.None
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "videoThumbnailIsAvailable:",
name: MPMoviePlayerThumbnailImageRequestDidFinishNotification,
object: nil)
let thumbnailTimes = 3.0
moviePlayer.requestThumbnailImagesAtTimes([thumbnailTimes],
timeOption: .NearestKeyFrame)
}
func videoThumbnailIsAvailable(notification: NSNotification){
if let player = moviePlayer{
let thumbnail =
notification.userInfo![MPMoviePlayerThumbnailImageKey] as? UIImage
if let image = thumbnail{
/* We got the thumbnail image. You can now use it here */
println("Thumbnail image = \(image)")
}
}
回答by Avt
Swift 2 code:
斯威夫特 2 代码:
func previewImageForLocalVideo(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
}
}
回答by Hiren Panchal
For Swift 3.0
对于 Swift 3.0
func createThumbnailOfVideoFromFileURL(_ strVideoURL: String) -> UIImage?{
let asset = AVAsset(url: URL(string: strVideoURL)!)
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 {
/* error handling here */
}
return nil }
回答by Rajender Kumar
Swift 4
斯威夫特 4
func generateThumbnail(for asset:AVAsset) -> UIImage? {
let assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
let time = CMTimeMake(value: 1, timescale: 2)
let img = try? assetImgGenerate.copyCGImage(at: time, actualTime: nil)
if img != nil {
let frameImg = UIImage(cgImage: img!)
return frameImg
}
return nil
}
How to use:
如何使用:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true) {
switch mediaType {
case kUTTypeMovie:
guard info[UIImagePickerController.InfoKey.mediaType] != nil, let url = info[UIImagePickerController.InfoKey.mediaURL] as? URL else { return }
let asset = AVAsset(url: url)
guard let img = self.generateThumbnail(for: asset) else {
print("Error: Thumbnail can be generated.")
return
}
print("Image Size: \(img.size)")
break
default:
break
}
}
}
回答by Rohan Aryan
For Swift 5
对于 Swift 5
import AVKit
Code:
代码:
// Get Thumbnail Image from URL
fileprivate 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 ::Take one Image View
用法 ::拍摄一张图片
@IBOutlet weak var imgThumbnail: UIImageView!
Then after call getThumbnailFromUrl
method for thumbnail with URL String
as parameter
然后在getThumbnailFromUrl
以 URLString
为参数调用缩略图的方法之后
self.getThumbnailFromUrl(videoURL) { [weak self] (img) in
guard let _ = self else { return }
if let img = img {
self?.imgThumbnail.image = img
}
}
pls try this if it is use full then pls comment Thank you
请尝试这个,如果它使用完整然后请评论 谢谢
回答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.
也许这对面临同样问题的其他人有用。我需要一个简单的解决方案来为图像、PDF 和视频创建缩略图。为了解决这个问题,我创建了以下库。
https://github.com/prine/ROThumbnailGenerator
https://github.com/prine/ROThumbnailGenerator
The usage is very straightforward:
var thumbnailImage = ROThumbnail.getThumbnail(url)
用法非常简单:
var thumbnailImage = 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.
它在内部具有三种不同的实现,并根据文件扩展名创建缩略图。如果您需要另一个文件扩展名的缩略图创建者,您可以轻松添加自己的实现。