针对视频处理,分别给出javax与javacv的演示demo
时间: 2024-01-24 13:17:01 浏览: 33
1. javax演示demo
下面是使用javax实现视频处理的演示demo,它可以打开一个视频文件,播放视频并进行截屏操作:
```java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import javax.swing.filechooser.FileView;
public class VideoPlayer extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel controlPanel;
private JLabel videoLabel;
private JButton playButton;
private JButton pauseButton;
private JButton stopButton;
private JButton screenShotButton;
private JFileChooser fileChooser;
private Timer timer;
private int delay = 100;
private VideoCapture videoCapture;
private BufferedImage currentImage;
private boolean isPlaying;
public VideoPlayer() {
setTitle("Video Player");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(640, 480));
setLocationRelativeTo(null);
contentPane = new JPanel(new BorderLayout());
videoLabel = new JLabel();
Border border = BorderFactory.createLineBorder(Color.BLACK, 5);
videoLabel.setBorder(border);
contentPane.add(videoLabel, BorderLayout.CENTER);
controlPanel = new JPanel(new FlowLayout());
playButton = new JButton("Play");
pauseButton = new JButton("Pause");
stopButton = new JButton("Stop");
screenShotButton = new JButton("Screen Shot");
playButton.addActionListener(this);
pauseButton.addActionListener(this);
stopButton.addActionListener(this);
screenShotButton.addActionListener(this);
controlPanel.add(playButton);
controlPanel.add(pauseButton);
controlPanel.add(stopButton);
controlPanel.add(screenShotButton);
contentPane.add(controlPanel, BorderLayout.SOUTH);
setContentPane(contentPane);
pack();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == playButton) {
play();
} else if (e.getSource() == pauseButton) {
pause();
} else if (e.getSource() == stopButton) {
stop();
} else if (e.getSource() == screenShotButton) {
screenShot();
}
}
private void play() {
if (isPlaying) {
return;
}
if (videoCapture == null) {
openFile();
if (videoCapture == null) {
return;
}
}
timer = new Timer(delay, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
currentImage = videoCapture.getImage();
if (currentImage != null) {
videoLabel.setIcon(new ImageIcon(currentImage));
}
}
});
timer.start();
isPlaying = true;
}
private void pause() {
if (!isPlaying) {
return;
}
if (timer != null) {
timer.stop();
}
isPlaying = false;
}
private void stop() {
if (!isPlaying) {
return;
}
if (timer != null) {
timer.stop();
}
videoCapture.release();
videoCapture = null;
currentImage = null;
videoLabel.setIcon(null);
isPlaying = false;
}
private void screenShot() {
if (currentImage == null) {
return;
}
String fileName = JOptionPane.showInputDialog(this, "Please input the file name:", "Screen Shot",
JOptionPane.PLAIN_MESSAGE);
if (fileName == null || fileName.trim().length() == 0) {
return;
}
File file = new File(fileName + ".png");
try {
ImageIO.write(currentImage, "png", file);
JOptionPane.showMessageDialog(this, "Screen shot saved successfully!", "Screen Shot",
JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Failed to save screen shot: " + e.getMessage(), "Screen Shot",
JOptionPane.ERROR_MESSAGE);
}
}
private void openFile() {
fileChooser = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
fileChooser.setDialogTitle("Open Video File");
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setFileFilter(new FileNameExtensionFilter("Video Files", "mp4", "avi", "flv", "mkv"));
fileChooser.setFileView(new FileView() {
@Override
public Icon getIcon(File f) {
String extension = Utils.getExtension(f.getName());
if (extension != null && Utils.isVideo(extension)) {
return super.getIcon(f);
}
return null;
}
});
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
videoCapture = new VideoCapture(file.getAbsolutePath());
}
}
private static class Utils {
public static String getExtension(String fileName) {
int index = fileName.lastIndexOf('.');
if (index >= 0 && index < fileName.length() - 1) {
return fileName.substring(index + 1).toLowerCase();
}
return null;
}
public static boolean isVideo(String extension) {
return "mp4".equals(extension) || "avi".equals(extension) || "flv".equals(extension)
|| "mkv".equals(extension);
}
public static BufferedImage resize(BufferedImage image, int width, int height) {
Image tmp = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = resized.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return resized;
}
}
private static class VideoCapture {
private FFmpegFrameGrabber grabber;
private long duration;
public VideoCapture(String filePath) {
grabber = new FFmpegFrameGrabber(filePath);
try {
grabber.start();
duration = grabber.getLengthInTime();
} catch (Exception e) {
e.printStackTrace();
}
}
public BufferedImage getImage() {
try {
Frame frame = grabber.grab();
if (frame == null) {
return null;
}
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage image = converter.getBufferedImage(frame);
if (image == null) {
return null;
}
double width = image.getWidth();
double height = image.getHeight();
double ratio = width / height;
double targetWidth = videoLabel.getWidth();
double targetHeight = videoLabel.getHeight();
double targetRatio = targetWidth / targetHeight;
int x, y, w, h;
if (ratio > targetRatio) {
w = (int) targetWidth;
h = (int) (targetWidth / ratio);
x = 0;
y = (int) ((targetHeight - h) / 2);
} else {
w = (int) (targetHeight * ratio);
h = (int) targetHeight;
x = (int) ((targetWidth - w) / 2);
y = 0;
}
image = Utils.resize(image, w, h);
BufferedImage newImage = new BufferedImage((int) targetWidth, (int) targetHeight,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = newImage.createGraphics();
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, newImage.getWidth(), newImage.getHeight());
g2d.drawImage(image, x, y, null);
g2d.dispose();
return newImage;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void release() {
try {
grabber.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
public long getDuration() {
return duration;
}
}
public static void main(String[] args) {
new VideoPlayer();
}
}
```
2. javacv演示demo
下面是使用javacv实现视频处理的演示demo,它可以打开一个视频文件,播放视频并进行截屏操作:
```java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import javax.swing.filechooser.FileView;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.javacpp.Loader;
import org.bytedeco.javacv.CanvasFrame;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.opencv.global.opencv_imgproc;
import org.bytedeco.opencv.opencv_core.IplImage;
public class VideoPlayer extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel controlPanel;
private JLabel videoLabel;
private JButton playButton;
private JButton pauseButton;
private JButton stopButton;
private JButton screenShotButton;
private JFileChooser fileChooser;
private Timer timer;
private int delay = 100;
private FFmpegFrameGrabber grabber;
private Java2DFrameConverter converter;
private BufferedImage currentImage;
private boolean isPlaying;
public VideoPlayer() {
setTitle("Video Player");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(640, 480));
setLocationRelativeTo(null);
contentPane = new JPanel(new BorderLayout());
videoLabel = new JLabel();
Border border = BorderFactory.createLineBorder(Color.BLACK, 5);
videoLabel.setBorder(border);
contentPane.add(videoLabel, BorderLayout.CENTER);
controlPanel = new JPanel(new FlowLayout());
playButton = new JButton("Play");
pauseButton = new JButton("Pause");
stopButton = new JButton("Stop");
screenShotButton = new JButton("Screen Shot");
playButton.addActionListener(this);
pauseButton.addActionListener(this);
stopButton.addActionListener(this);
screenShotButton.addActionListener(this);
controlPanel.add(playButton);
controlPanel.add(pauseButton);
controlPanel.add(stopButton);
controlPanel.add(screenShotButton);
contentPane.add(controlPanel, BorderLayout.SOUTH);
setContentPane(contentPane);
pack();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == playButton) {
play();
} else if (e.getSource() == pauseButton) {
pause();
} else if (e.getSource() == stopButton) {
stop();
} else if (e.getSource() == screenShotButton) {
screenShot();
}
}
private void play() {
if (isPlaying) {
return;
}
if (grabber == null) {
openFile();
if (grabber == null) {
return;
}
}
timer = new Timer(delay, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Frame frame = grabber.grab();
if (frame != null) {
currentImage = converter.getBufferedImage(frame);
videoLabel.setIcon(new ImageIcon(currentImage));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
timer.start();
isPlaying = true;
}
private void pause() {
if (!isPlaying) {
return;
}
if (timer != null) {
timer.stop();
}
isPlaying = false;
}
private void stop() {
if (!isPlaying) {
return;
}
if (timer != null) {
timer.stop();
}
try {
grabber.stop();
} catch (Exception e) {
e.printStackTrace();
}
grabber = null;
currentImage = null;
videoLabel.setIcon(null);
isPlaying = false;
}
private void screenShot() {
if (currentImage == null) {
return;
}
String fileName = JOptionPane.showInputDialog(this, "Please input the file name:", "Screen Shot",
JOptionPane.PLAIN_MESSAGE);
if (fileName == null || fileName.trim().length() == 0) {
return;
}
File file = new File(fileName + ".png");
try {
ImageIO.write(currentImage, "png", file);
JOptionPane.showMessageDialog(this, "Screen shot saved successfully!", "Screen Shot",
JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Failed to save screen shot: " + e.getMessage(), "Screen Shot",
JOptionPane.ERROR_MESSAGE);
}
}
private void openFile() {
fileChooser = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
fileChooser.setDialogTitle("Open Video File");
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setFileFilter(new FileNameExtensionFilter("Video Files", "mp4", "avi", "flv", "mkv"));
fileChooser.setFileView(new FileView() {
@Override
public Icon getIcon(File f) {
String extension = Utils.getExtension(f.getName());
if (extension != null && Utils.isVideo(extension)) {
return super.getIcon(f);
}
return null;
}
});
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
grabber = new FFmpegFrameGrabber(file.getAbsolutePath());
converter = new Java2DFrameConverter();
try {
grabber.start();
} catch (org.bytedeco.javacv.FrameGrabber.Exception e) {
e.printStackTrace();
}
}
}
private static class Utils {
public static String getExtension(String fileName) {
int index = fileName.lastIndexOf('.');
if (index >= 0 && index < fileName.length() - 1) {
return fileName.substring(index + 1).toLowerCase();
}
return null;
}
public static boolean isVideo(String extension) {
return "mp4".equals(extension) || "avi".equals(extension) || "flv".equals(extension)
|| "mkv".equals(extension);
}
public static BufferedImage resize(BufferedImage image, int width, int height) {
Image tmp = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = resized.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return resized;
}
}
public static void main(String[] args) {
Loader.load(opencv_imgproc.class);
Loader.load(avcodec.class);
new VideoPlayer();
}
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)