【问题标题】:How to extract images from a video?如何从视频中提取图像?
【发布时间】:2012-05-16 19:24:37
【问题描述】:

谁能告诉我如何从视频中提取图像?到目前为止,我尝试过的是遵循这些:

等等。然后我做了这个:

源代码:

- (void)viewDidLoad
{
    videoPicker = [[UIImagePickerController alloc] init];
    [videoPicker setDelegate:self];
    videoPicker.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
    NSArray *mediaTypesAllowed = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    videoPicker.mediaTypes = mediaTypesAllowed;
    videoPicker.view.hidden = YES;
}


-(IBAction)imgPickerController
{
    [self presentModalViewController:videoPicker animated:YES];
    videoPicker.view.hidden = NO;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // e.g.
    NSString *tempFilePath = [(NSURL *)[info valueForKey:UIImagePickerControllerMediaURL] absoluteString];

    NSLog(@"didFinishPickingMediaWithInfo: %@",tempFilePath);

    // e.g. /private/var/mobile/Applications/D1E784A4-EC1A-402B-81BF-F36D3A08A332/tmp/capture/capturedvideo.MOV
    tempFilePath = [tempFilePath substringFromIndex:16];

    NSLog(@"didFinishPickingMediaWithInfo: %@",tempFilePath);
    NSLog(@"===Try to save video to camera roll.===");
    NSLog(@"UIVideoAtPathIsCompatibleWithSavedPhotosAlbum: %@",UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(tempFilePath)? @"YES":@"NO");

    // Check if the video file can be saved to camera roll.
    if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(tempFilePath))
    {
        // YES. Copy it to the camera roll.
        UISaveVideoAtPathToSavedPhotosAlbum(tempFilePath, self, @selector(video:didFinishSavingWithError:contextInfo:),(__bridge_retained void *)tempFilePath );
    }

    [self dismissModalViewControllerAnimated:YES];
}

- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(NSString *)contextInfo
{
    NSLog(@"didFinishSavingWithError--videoPath in camera roll:%@",videoPath);
    NSLog(@"didFinishSavingWithError--videoPath in temp directory:%@",contextInfo);

    // The thumbnail jpg should located in this directory.
    NSString *thumbnailDirectory = [[contextInfo stringByDeletingLastPathComponent] stringByDeletingLastPathComponent];

    // Debug info. list all files in the directory of the video file.
    // e.g. /private/var/mobile/Applications/D1E784A4-EC1A-402B-81BF-F36D3A08A332/tmp/capture
    NSLog(@"%@",[contextInfo stringByDeletingLastPathComponent]);
    NSLog(@"%@",[[[NSFileManager defaultManager] contentsOfDirectoryAtPath:[contextInfo stringByDeletingLastPathComponent] error:nil] description]);

    // Debug info. list all files in the parent directory of the video file, i.e. the "~/tmp" directory.
    // e.g. /private/var/mobile/Applications/D1E784A4-EC1A-402B-81BF-F36D3A08A332/tmp
    NSLog(@"%@",thumbnailDirectory);
    NSLog(@"%@",[[[NSFileManager defaultManager] contentsOfDirectoryAtPath:thumbnailDirectory error:nil] description]);
    ///////////////////

    // Find the thumbnail for the video just recorded.
    NSString *file,*latestFile;

    NSDate *latestDate = [NSDate distantPast];
    NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:[[contextInfo stringByDeletingLastPathComponent]stringByDeletingLastPathComponent]];

    // Enumerate all files in the ~/tmp directory
    while (file = [dirEnum nextObject])
    {
        // Only check files with jpg extension.
        if ([[file pathExtension] isEqualToString: @"jpg"]) 
        {
            NSLog(@"***latestDate:%@",latestDate);
            NSLog(@"***file name:%@",file);
            NSLog(@"***NSFileSize:%@", [[dirEnum fileAttributes] valueForKey:@"NSFileSize"]);
            NSLog(@"***NSFileModificationDate:%@", [[dirEnum fileAttributes] valueForKey:@"NSFileModificationDate"]);

            // Check if current jpg file is the latest one.
            if ([(NSDate *)[[dirEnum fileAttributes] valueForKey:@"NSFileModificationDate"] compare:latestDate] == NSOrderedDescending)
            {
                latestDate = [[dirEnum fileAttributes] valueForKey:@"NSFileModificationDate"];
                latestFile = file;
                NSLog(@"***latestFile changed:%@",latestFile);
            }
        }
    }

    // The thumbnail path.
    latestFile = [NSTemporaryDirectory() stringByAppendingPathComponent:latestFile];
    NSLog(@"****** The thumbnail file should be this one:%@",latestFile);

    UIImage *img = [[UIImage alloc] initWithContentsOfFile:latestFile];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(150, 150, 100, 100)];
    [imgView setImage:img];
    imgView.layer.borderWidth = 2.0;
    [self.view addSubview:imgView];

    // Your code ...
    // Your code ...
    // Your code ...
}

在做完这一切之后,我仍然没有到达我想到达的地方。我仍然无法获取图像。我现在卡住了。请任何人帮助我!!!谢谢 :)

【问题讨论】:

    标签: ios image video uiimagepickercontroller


    【解决方案1】:

    从电影中提取缩略图的简单方法是使用MPMoviePlayerController 类及其- thumbnailImageAtTime:timeOption: 方法。

    例如,您有一个文件路径 url:

    NSURL *tempFilePathURL = ...;
    MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL: tempFilePathURL];
    UIImage *thumbnail = [player thumbnailImageAtTime:THUMBNAIL_TIME timeOption:MPMovieTimeOptionExact];
    [player release];
    

    我在我的代码中使用它并且它有效。

    【讨论】:

    • 你能告诉我如何获得这个缩略图的路径和扩展名吗??
    • 根据我的示例,您将获得 UIImage 对象。然后您可以将其保存为 png 或 jpg。
    【解决方案2】:

    thumbnailImageAtTime:timeOption 自 iOS 7.0 起已弃用。 这是另一种选择

    + (UIImage *)extractFirstFrameFromFilepath:(NSString *)filepath
    {
        AVURLAsset *movieAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:filepath] options:nil];
        AVAssetImageGenerator *assetImageGemerator = [[AVAssetImageGenerator alloc] initWithAsset:movieAsset];
        assetImageGemerator.appliesPreferredTrackTransform = YES;
        CGImageRef frameRef = [assetImageGemerator copyCGImageAtTime:CMTimeMake(1, 2) actualTime:nil error:nil];
        return [[UIImage alloc] initWithCGImage:frameRef];
    }
    

    【讨论】:

    • 我们可以重写这个来浏览整个视频吗?或者可能每 1 秒一次。
    【解决方案3】:

    斯威夫特版本

        func getThumbOfVideo(fileURL: URL) -> UIImage? {
            let movieAsset = AVURLAsset(url: fileURL)
            let assetImageGenerator = AVAssetImageGenerator(asset: movieAsset)
            assetImageGenerator.appliesPreferredTrackTransform = true
    
            var thumbnail: UIImage?
            do {
                let cgImage = try assetImageGenerator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1000), actualTime: nil)
                thumbnail = UIImage(cgImage: cgImage)
            } catch {
                print(error)
            }
    
            return thumbnail
        }
    

    如果您在整个视频中都需要缩略图数组,请使用 AVAssetImageGenerator 类的以下 API

    func generateCGImagesAsynchronously(forTimes requestedTimes: [NSValue], 
                      completionHandler handler: @escaping AVAssetImageGeneratorCompletionHandler)
    

    为所需的缩略图分辨率设置以下属性

    assetImageGenerator.maximumSize

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-27
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多