从库中选取的视频的 UIImagePickerController 缩略图

发布于 2024-11-02 10:43:52 字数 1000 浏览 1 评论 0 原文

我正在尝试使用 UIImagePickerController 获取从库中拾取的视频的缩略图。

这是我的代码。如果我使用相机录制视频,我可以获得视频的缩略图。但是,如果我从库中选取视频,则无法获取缩略图。有人知道为什么吗?

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];

    if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
        NSURL *mediaUrl = [info objectForKey:UIImagePickerControllerMediaURL];

        MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:mediaUrl];
        moviePlayer.shouldAutoplay = NO;
        UIImage *thumbnail = [[moviePlayer thumbnailImageAtTime:0.0 timeOption:MPMovieTimeOptionNearestKeyFrame] retain];
        [imageView setImage:thumbnail];  //imageView is a UIImageView

        [moviePlayer release];
        [thumbnail release];
        [self dismissModalViewControllerAnimated:YES];
    }
}

I am trying to get the thumbnail of the video which is pick up from library using the UIImagePickerController.

Here is my code. I can get the the thumbnail of video if I using the camera to record a video. But I can not get the thumbnail if I pick up a video from the library. Anybody know why?

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];

    if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
        NSURL *mediaUrl = [info objectForKey:UIImagePickerControllerMediaURL];

        MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:mediaUrl];
        moviePlayer.shouldAutoplay = NO;
        UIImage *thumbnail = [[moviePlayer thumbnailImageAtTime:0.0 timeOption:MPMovieTimeOptionNearestKeyFrame] retain];
        [imageView setImage:thumbnail];  //imageView is a UIImageView

        [moviePlayer release];
        [thumbnail release];
        [self dismissModalViewControllerAnimated:YES];
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

彩扇题诗 2024-11-09 10:43:52

我遇到了一个半相关的问题,最终放弃使用 MPMoviePlayer 生成缩略图。尝试使用 此处。这是我自己的示例代码,它获取单个缩略图。您需要包含 AVFoundation 框架。

AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:vidPath 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];
UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
CGImageRelease(image);
[gen release];

I had a semi-related problem, and eventually abandoned using MPMoviePlayer to generate thumbnails. Try using AVAssetImageGenerator instead. Apple discusses using AVAssetImageGenerator to create thumbnails here. Here is my own sample code, which grabs a single thumbnail image. You will need to include the AVFoundation framework.

AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:vidPath 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];
UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
CGImageRelease(image);
[gen release];
怀中猫帐中妖 2024-11-09 10:43:52

AssetsLibrary 框架正是您所需要的使用 ALAssetsLibraryALAsset 类。此代码适用于照片和视频,缩略图与您在选择器中看到的完全相同。

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [[ALAssetsLibrary new] assetForURL:info[UIImagePickerControllerReferenceURL] resultBlock:^(ALAsset *asset) {
        imageView.image = [UIImage imageWithCGImage:asset.thumbnail];
    } failureBlock:^(NSError *error) {
        // handle error
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
}

请注意,iOS 8 上的照片流相册存在错误,请参阅 ALAssetsLibrary assetForURL:对于 iOS 8.1 中“我的照片流”中的照片始终返回 nil 作为解决方法。

The AssetsLibrary framework has exactly what you need with the ALAssetsLibrary and ALAsset classes. This code work for both photos and videos and the thumbnail image is exactly the same as you see in the picker.

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [[ALAssetsLibrary new] assetForURL:info[UIImagePickerControllerReferenceURL] resultBlock:^(ALAsset *asset) {
        imageView.image = [UIImage imageWithCGImage:asset.thumbnail];
    } failureBlock:^(NSError *error) {
        // handle error
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
}

Note that there is a bug on iOS 8 with Photo Stream albums, see ALAssetsLibrary assetForURL: always returning nil for photos in “My Photo Stream” in iOS 8.1 for a workaround.

友谊不毕业 2024-11-09 10:43:52
func videoSnapshot(filePathLocal:URL) -> UIImage? {
    do
    {
        let asset = AVURLAsset(url: filePathLocal)
        let imgGenerator = AVAssetImageGenerator(asset: asset)
        imgGenerator.appliesPreferredTrackTransform = true
        let cgImage = try imgGenerator.copyCGImage(at:CMTimeMake(Int64(0), Int32(1)),actualTime: nil)
        let thumbnail = UIImage(cgImage: cgImage)
        return thumbnail
    }
    catch let error as NSError
    {
        print("Error generating thumbnail: \(error)")
        return nil
    }
}
func videoSnapshot(filePathLocal:URL) -> UIImage? {
    do
    {
        let asset = AVURLAsset(url: filePathLocal)
        let imgGenerator = AVAssetImageGenerator(asset: asset)
        imgGenerator.appliesPreferredTrackTransform = true
        let cgImage = try imgGenerator.copyCGImage(at:CMTimeMake(Int64(0), Int32(1)),actualTime: nil)
        let thumbnail = UIImage(cgImage: cgImage)
        return thumbnail
    }
    catch let error as NSError
    {
        print("Error generating thumbnail: \(error)")
        return nil
    }
}
落叶缤纷 2024-11-09 10:43:52

Swift 5 及更高版本

func thumbnailForVideo(url: URL) -> UIImage? {
    let asset = AVAsset(url: url)
    let assetImageGenerator = AVAssetImageGenerator(asset: asset)
    assetImageGenerator.appliesPreferredTrackTransform = true

    var time = asset.duration
    time.value = min(time.value, 2)

    do {
        let imageRef = try assetImageGenerator.copyCGImage(at: time, actualTime: nil)
        return UIImage(cgImage: imageRef)
    } catch {
        print("failed to create thumbnail")
        return nil
    }
}

Swift 5 and above

func thumbnailForVideo(url: URL) -> UIImage? {
    let asset = AVAsset(url: url)
    let assetImageGenerator = AVAssetImageGenerator(asset: asset)
    assetImageGenerator.appliesPreferredTrackTransform = true

    var time = asset.duration
    time.value = min(time.value, 2)

    do {
        let imageRef = try assetImageGenerator.copyCGImage(at: time, actualTime: nil)
        return UIImage(cgImage: imageRef)
    } catch {
        print("failed to create thumbnail")
        return nil
    }
}
荭秂 2024-11-09 10:43:52

Swift 3.1

我创建了一个类函数并在参数中传递你的 url

class func captureThumbnail(withVideoURL videoURL:URL,secs:Int,preferredTimeScale scale:Int,completionHandler:((UIImage?) ->Void)?) -> Void
{
    //let seconds : Int64 = 10
    // let preferredTimeScale : Int32 = 1

    DispatchQueue.global().async {

        do
        {
            let asset = AVURLAsset(url: videoURL)

            let imgGenerator = AVAssetImageGenerator(asset: asset)
            imgGenerator.appliesPreferredTrackTransform = true
            let cgImage = try imgGenerator.copyCGImage(at:CMTimeMake(Int64(secs), Int32(scale)),actualTime: nil)
            let thumbnail = UIImage(cgImage: cgImage)
            completionHandler?(thumbnail)
        }
        catch let error as NSError
        {
            print("Error generating thumbnail: \(error)")
            completionHandler?(nil)
        }
    }
}

Swift 3.1

I have create a class function and pass your url in param

class func captureThumbnail(withVideoURL videoURL:URL,secs:Int,preferredTimeScale scale:Int,completionHandler:((UIImage?) ->Void)?) -> Void
{
    //let seconds : Int64 = 10
    // let preferredTimeScale : Int32 = 1

    DispatchQueue.global().async {

        do
        {
            let asset = AVURLAsset(url: videoURL)

            let imgGenerator = AVAssetImageGenerator(asset: asset)
            imgGenerator.appliesPreferredTrackTransform = true
            let cgImage = try imgGenerator.copyCGImage(at:CMTimeMake(Int64(secs), Int32(scale)),actualTime: nil)
            let thumbnail = UIImage(cgImage: cgImage)
            completionHandler?(thumbnail)
        }
        catch let error as NSError
        {
            print("Error generating thumbnail: \(error)")
            completionHandler?(nil)
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文