package implementation;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.media.Buffer;
import javax.media.Player;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class PhotoCatch {
private Buffer buffer;
private BufferToImage bufferToImage;
private Image image;
private FrameGrabbingControl fgc;
public PhotoCatch(Player player){
fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
this.buffer = fgc.grabFrame();
bufferToImage = new BufferToImage((VideoFormat) buffer.getFormat());
image = bufferToImage.createImage(this.buffer);
}
public void upDate(){
this.buffer = fgc.grabFrame();
bufferToImage = new BufferToImage((VideoFormat) buffer.getFormat());
image = bufferToImage.createImage(this.buffer);
}
public int getImageWidth(){
return image.getWidth(null);
}
public int getImageHeight(){
return image.getHeight(null);
}
public void saveImage(String address){
saveImage(image,address);
}
private void saveImage(Image image, String path) {
if(this.image == null)
System.out.println("image is null");
BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
g2.drawImage(image, null, null);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JPEGImageEncoder je = JPEGCodec.createJPEGEncoder(fos);
JPEGEncodeParam jp = je.getDefaultJPEGEncodeParam(bi);
jp.setQuality(0.5f, false);
je.setJPEGEncodeParam(jp);
try {
je.encode(bi);
fos.close();
} catch (ImageFormatException e) {
// TODO Auto-generated catch block
System.out.println("错误4");
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("错误5");
}
}
}
每次需要重新截图时候,一定要进行更新!因为JMF API 中
Class BufferToImage
This is a utility class to convert a video Buffer object to an AWTImage object that you can then render using AWT methods.
You can use this class in conjunction with the FrameGrabbingControl to grab frames from the video renderer and manipulate the image.
bufferToImage是共用的,如果不进行更新的话。buffer会失效,导致无法转换为image,也就无法成功截图了!

本文介绍如何利用JMFAPI中的FrameGrabbingControl模块从视频流中抓取帧,并通过BufferToImage类将视频缓冲区转换为AWT图像,进而实现视频截图的功能。关键步骤包括初始化Player对象、获取FrameGrabbingControl控制、抓取帧并将其转换为图像,最后保存图像到文件系统。注意,为了确保截图的成功,每次抓取帧后都需要更新缓冲区。
185

被折叠的 条评论
为什么被折叠?



