First frame of a video using AVFoundation

霸气de小男生 提交于 2019-12-31 10:23:10

问题


I'm trying to get the first frame of a video using the classes in AVFoundation. But it appears to not be getting an image at all.

My code currently looks like this

AVURLAsset* asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:videoPath] options:nil];
AVAssetImageGenerator* imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
UIImage* image = [UIImage imageWithCGImage:[imageGenerator copyCGImageAtTime:CMTimeMake(0, 1) actualTime:nil error:nil]];
[videoFrame setImage:image];

The value of video path is /var/mobile/Applications/02F42CBF-D8BD-4155-85F2-8CF1E55B5023/Documents/videos/1334300431637030.mp4 which is definitely a video, since I can play it with MPMoviePlayerViewController. I'm not sure what I'm doing wrong but any suggestions would be helpful.

Thanks.


回答1:


I solved it. Apparently using [NSURL fileURLWithPath:videoPath] instead of [NSURL URLWithString:videoPath] makes all the difference.




回答2:


I used null0pointer solution but in some videos I recieved the first frame rotated. To resolve this issue I set to TRUE the appliesPreferredTrackTransform property of AVAssetImageGenerator. And this code looks like this:

AVURLAsset* asset = [AVURLAsset URLAssetWithURL:fileURL options:nil];
AVAssetImageGenerator* imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
[imageGenerator setAppliesPreferredTrackTransform:TRUE];
UIImage* image = [UIImage imageWithCGImage:[imageGenerator copyCGImageAtTime:CMTimeMake(0, 1) actualTime:nil error:nil]];
[self.imageView setImage:image];



回答3:


Doing this in Swift 4.0:

            // Assumes you have a local `fileURL`

            var avAsset = AVURLAsset(url: fileURL, options: nil)
            var imageGenerator = AVAssetImageGenerator(asset: avAsset)
            imageGenerator.appliesPreferredTrackTransform = true
            var thumbnail: UIImage?

            do {
                thumbnail = try UIImage(cgImage: imageGenerator.copyCGImage(at: CMTime(seconds: 0, preferredTimescale: 1), actualTime: nil))
            } catch let e as NSError {
                print("Error: \(e.localizedDescription)")
            }


来源:https://stackoverflow.com/questions/10221242/first-frame-of-a-video-using-avfoundation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!