使用xuggler获取视频的截图/快照的正确方法是什么?

时间:2013-07-15 17:44:58

标签: java video-capture xuggler

我想使用xuggler从视频创建图像。提供的示例代码在一个间隔中从视频生成图像,我对其进行了修改,使其仅从视频生成一个图像。但是,看起来它实际上是在整个视频中循环,而不仅仅是拍摄特定时间的快照然后结束。

如何在不循环整个视频的情况下从视频中正确生成一个图像?在较短的视频上这很好,但在hr +视频中,这将成为一个巨大的问题。

以下是我的代码:

import javax.imageio.ImageIO;

import java.io.File;

import java.awt.image.BufferedImage;
import java.util.Random;

import com.xuggle.mediatool.IMediaReader;
import com.xuggle.mediatool.MediaListenerAdapter;
import com.xuggle.mediatool.ToolFactory;
import com.xuggle.mediatool.event.IVideoPictureEvent;
import com.xuggle.xuggler.Global;

public class Test extends MediaListenerAdapter {
    public static final double SECONDS_BETWEEN_FRAMES = 1;
    public static final long MICRO_SECONDS_BETWEEN_FRAMES = (long)(Global.DEFAULT_PTS_PER_SECOND * SECONDS_BETWEEN_FRAMES);

    private int mVideoStreamIndex = -1;
    boolean takeImage = true;

    public static void main(String[] args) {
        new Test("src/main/Wildlife_ 512kb, hkf.mp4");
    }

    public Test(String filename) {
        System.out.println("starting the xuggler");
        IMediaReader reader = ToolFactory.makeReader(filename);
        reader.setBufferedImageTypeToGenerate(BufferedImage.TYPE_3BYTE_BGR);
        reader.addListener(this);
        while (reader.readPacket() == null) { do { } while(false); }
    }

    public void onVideoPicture(IVideoPictureEvent event) {
        try {
            if (event.getStreamIndex() != mVideoStreamIndex) {
                if (-1 == mVideoStreamIndex) {
                    mVideoStreamIndex = event.getStreamIndex();
                } else {
                    return;
                }
            }

            if (event.getTimeStamp() > MICRO_SECONDS_BETWEEN_FRAMES && takeImage) {
                Random random = new Random();
                File file = new File("/Users/yao/__TEMP__/media_upload_temp/" + random.nextInt(Integer.MAX_VALUE) + ".png");
                ImageIO.write(event.getImage(), "png", file);

                double seconds = ((double)event.getTimeStamp()) / Global.DEFAULT_PTS_PER_SECOND;
                System.out.printf("at elapsed time of %6.3f seconds wrote: %s\n", seconds, file);

                takeImage = false;
            }
        } catch (Exception e) { e.printStackTrace(); }
    }
}

1 个答案:

答案 0 :(得分:2)

基本上,我只是给了一个布尔字段,并用它来管理一个图像被捕获后何时突破循环/视频。

 while (reader.readPacket() == null) {
                if (!takeImage) {
                    reader.removeListener(this);
                    break;
                }
            }