从系统摄像头拍摄快照的Java程序
最好对Java的 Swing 类有一个简短的了解,因为它被应用于实现中,因为每当需要处理图像或处理二维矩阵作为输出或使用它时在Java中生成输出,Swing 类在实现相同的过程中发挥作用。
我们将使用 Netbeans IDE o 创建 GUI 应用程序,因为它是一个精心制作的开源 IDE,提供组件检查器、小部件拖放、调试器、对象浏览器等功能,并且无需导入 JAR文件不太可能在其他 IDE 中看到,例如 eclipse。现在,这使此 IDE 比其他 IDE 更具优势。
概念:
基本上,该程序分为 2 部分。一个是使用摆动控件完成的设计部分。另一部分是一些用于捕获图像的代码部分。
- 在设计部分,我使用了swing控件来设计界面。我们只需要从调色板中拖放控件。这里使用了 2 个标签和 1 个按钮。 第一个标签名称是“ lblclose ”。在那里,我设置了一个 PNG 图像并编写了关于events-> action execution的代码。当您单击该图像时,输出窗口将关闭。为此,我使用了dispose() 方法。第二个标签名称是 ' lblphoto' 。在这里您可以在运行程序时看到您的图像。 当您运行代码时,网络摄像头将打开。在这里,我使用了一个名为“ btnclick ”的按钮。您可以看到一个按钮单击。当您单击按钮时,图像将被捕获在您的“ lblphoto ”标签中。
- 在代码部分,我使用了网络摄像头,将其命名为“wc”,即创建了一个网络摄像头对象。该库允许您直接从Java使用内置或外部网络摄像头。它旨在抽象常用的相机功能并支持多种捕获框架。然后通过open()函数,网络摄像头将打开。然后单击“单击”按钮后,您将捕获图像。然后根据标签的大小转换这个图像。然后将此图像分配给标签。然后创建并启动线程。
程序:
- 创建一个新的Java应用程序并在项目下进一步创建一个文件。 `
- 根据需要从位于右上角的调色板开始拖动工具包小部件。
- 单击面板区域的任意位置并转到属性以更改背景。
- 现在双击背景区域并选择任何颜色,然后按确定按钮。
- 现在开始在绘图区域上拖动小部件。
- 开始编写Java程序,如下所述。
- 选择需要导入的 JAR 文件库中的 JAR 文件。
执行:
步骤 1(a):通过单击“新建项目 → Java → Java应用程序”创建一个新的Java应用程序,并给出一个合适的项目名称。考虑一个用于说明目的的随机示例“ MyFirstFrame” ,然后单击“完成”。
步骤 1(b):要在同一个Java项目“MyFirstFrame”下创建“新文件”,请右键单击窗口左侧的项目名称,如下图所示单击,然后单击“完成”。 例如我的框架。Java
New -> JFrame Form and give a suitable file name
第 2 步:现在从位于窗口右侧的调色板中,根据要求开始拖动工具包小部件。要更改框架的背景颜色,我们需要先插入一个 JPanel 并更改其属性。
步骤3:单击面板区域的任意位置,转到“属性→背景”。
第四步:双击背景选项,选择符合要求选择的任意颜色,点击确定。
第五步:设置背景颜色后,将其他小部件拖到设计区域。在这里,我拖动了一个按钮和一个标签。名为 CLICK 和标签的按钮用于捕获图像。此外,还为标签提供了边框。
步骤 6(a):现在通过右键单击编写代码,如下所示
MyFrame.java → Split → Horizontally
步骤 6(b):然后会出现这个弹出窗口。这里点击' source '编写代码,再点击' design '进入设计。
步骤 7(a):添加 jar 文件,转到库。右键单击“库”并选择“添加 JAR/文件夹”。
步骤 7(b):选择 3 个 jar 文件,然后单击“打开”。要求如下:库中需要导入JAR文件,具体需要导入3个JAR文件
- bridj-0.7.0.jar
- slf4j-api-1.7.2.jar
- webcam-capture-0.3.12.jar
执行:
示例输入图像如下所示:
例子:
Java
// Java Program to Take a Snapshot From System Camera
package myfirstform;
// The goal of this import com.github.sarxos.webcam.Webcam
// is to allow integrated or USB-connected webcams
// to be accessed directly from java
// Using provided libraries users are able to
// read camera images and detect motion
import com.github.sarxos.webcam.Webcam;
// Provides classes for creating and modifying images*/
import java.awt.Image;
// Creates an ImageIcon from an array of bytes
// which were read from an image file containing
// a supported image format, such as GIF, JPG, PNG
import javax.swing.ImageIcon;
// Class
// Main class
public class MyFrame
extends javax.swing.JFrame implements Runnable {
// Creates new form MyFrame
public MyFrame()
{
// Initialising the components
initComponents();
// This is for the closing button
lblclose.setText("");
// Createing an image icon by adding path of image
ImageIcon img = new ImageIcon(
"C:\\Users\\dhannu\\Documents\\NetBeansProjects\\MyFirstForm\\src\\images\\sf.png");
// Creating an object of Image type
Image myimg = img.getImage();
// Creating a new image whose size is same as label
// size using algorithm - SCALE_SMOOTH
Image newimage = myimg.getScaledInstance(
lblclose.getWidth(), lblclose.getHeight(),
Image.SCALE_SMOOTH);
// Creating a image icon from new image
ImageIcon ic = new ImageIcon(newimage);
// Assigning the imageicon to the label
lblclose.setIcon(ic);
// Thread is created and started using
// start() method which begins thread execution
new Thread(this).start();
}
// generated code
// This method is called from within the constructor to
// initialize the form. WARNING: Do NOT modify this
// code. The content of this method is always
// regenerated by the Form Editor.
@SuppressWarnings("unchecked")
private void initComponents()
{
jPanel1 = new javax.swing.JPanel();
lblclose = new javax.swing.JLabel();
lblphoto = new javax.swing.JLabel();
btnclick = new javax.swing.JButton();
setDefaultCloseOperation(
javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
// Setting the background by providing
// Custom input bounds as parameters
jPanel1.setBackground(
new java.awt.Color(204, 204, 255));
lblclose.addMouseListener(
new java.awt.event.MouseAdapter() {
public void mouseClicked(
java.awt.event.MouseEvent evt)
{
lblcloseMouseClicked(evt);
}
});
lblphoto.setBorder(
javax.swing.BorderFactory.createLineBorder(
new java.awt.Color(0, 0, 0), 4));
// Click button
btnclick.setText("CLICK");
btnclick.addActionListener(
new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt)
{
btnclickActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout
= new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout
.createParallelGroup(javax.swing.GroupLayout
.Alignment.LEADING)
.addGroup(
jPanel1Layout.createSequentialGroup()
.addGap(51, 51, 51)
.addComponent(
lblphoto,
javax.swing.GroupLayout
.PREFERRED_SIZE,
143,
javax.swing.GroupLayout
.PREFERRED_SIZE)
.addPreferredGap(
javax.swing.LayoutStyle
.ComponentPlacement.RELATED,
34, Short.MAX_VALUE)
.addComponent(
lblclose,
javax.swing.GroupLayout
.PREFERRED_SIZE,
28,
javax.swing.GroupLayout
.PREFERRED_SIZE)
.addContainerGap())
.addGroup(
jPanel1Layout.createSequentialGroup()
.addGap(97, 97, 97)
.addComponent(btnclick)
.addContainerGap(
javax.swing.GroupLayout
.DEFAULT_SIZE,
Short.MAX_VALUE)));
jPanel1Layout.setVerticalGroup(
jPanel1Layout
.createParallelGroup(javax.swing.GroupLayout
.Alignment.LEADING)
.addGroup(
jPanel1Layout.createSequentialGroup()
.addGroup(
jPanel1Layout
.createParallelGroup(
javax.swing.GroupLayout
.Alignment.LEADING)
.addGroup(
jPanel1Layout
.createSequentialGroup()
.addContainerGap()
.addComponent(
lblclose,
javax.swing
.GroupLayout
.PREFERRED_SIZE,
28,
javax.swing
.GroupLayout
.PREFERRED_SIZE))
.addGroup(
jPanel1Layout
.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(
lblphoto,
javax.swing
.GroupLayout
.PREFERRED_SIZE,
143,
javax.swing
.GroupLayout
.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(btnclick)
.addContainerGap(29,
Short.MAX_VALUE)));
javax.swing.GroupLayout layout
= new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout
.createParallelGroup(javax.swing.GroupLayout
.Alignment.LEADING)
.addComponent(
jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout
.PREFERRED_SIZE));
layout.setVerticalGroup(
layout
.createParallelGroup(javax.swing.GroupLayout
.Alignment.LEADING)
.addComponent(
jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout
.PREFERRED_SIZE));
pack();
setLocationRelativeTo(null);
}
// End of generate code
private void
lblcloseMouseClicked(java.awt.event.MouseEvent evt)
{
// Setting flag as false to stop the thread
// so that you can capture the snapshot
flag = false;
// Destroying and cleaning the JFrame window
// by the operating system\
// using dispose() method
dispose();
}
private void
btnclickActionPerformed(java.awt.event.ActionEvent evt)
{
flag = false;
}
// Main driver method
public static void main(String args[])
{
// Set the Nimbus look and feel
// If Nimbus(Java 6+) is not available
// stay with the default look and feel.
// Try block to check if any exceptions occur
try {
for (javax.swing.UIManager
.LookAndFeelInfo info :
javax.swing.UIManager
.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(
info.getClassName());
break;
}
}
}
// Catch blocks to handle exceptions
// First catch block to handle exception
// if class is not found
catch (ClassNotFoundException ex) {
java.util.logging.Logger
.getLogger(MyFrame.class.getName())
.log(java.util.logging.Level.SEVERE, null,
ex);
}
// Second catch block to handle for exception
// InstantiationException
// In generic, this exception is thrown
// rarely
catch (InstantiationException ex) {
java.util.logging.Logger
.getLogger(MyFrame.class.getName())
.log(java.util.logging.Level.SEVERE, null,
ex);
}
// 3rd catch block to handle
// IllegalAccessException
catch (IllegalAccessException ex) {
java.util.logging.Logger
.getLogger(MyFrame.class.getName())
.log(java.util.logging.Level.SEVERE, null,
ex);
}
// 4th catch block to handle Swing class
// UnsupportedLookAndFeelException
catch (javax.swing
.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger
.getLogger(MyFrame.class.getName())
.log(java.util.logging.Level.SEVERE, null,
ex);
}
//
// Create and display the form
java.awt.EventQueue.invokeLater(new Runnable() {
// Method run() which will later on
// over-ridden
public void run()
{
new MyFrame().setVisible(true);
}
});
}
// End of generated code
// Declaring variables
private javax.swing.JButton btnclick;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel lblclose;
private javax.swing.JLabel lblphoto;
Webcam wc;
// Initially setting flag as true
boolean flag = true;
// Overriding the run() method as
// created above already
// @Override
public void run()
{
// Creating a webcam object
wc = Webcam.getDefault();
// Method to open the camera
wc.open();
// Checking condition over flag which
// holds true for boolean true as
// above flag is declared true
while (flag) {
// An image is clicked
Image img = wc.getImage();
// Create a image whose size is same as label
img = img.getScaledInstance(
lblphoto.getWidth(), lblphoto.getHeight(),
Image.SCALE_SMOOTH);
// The clicked image is assigned to a Label
lblphoto.setIcon(new ImageIcon(img));
// Try block to check for thread exception
try {
// Putting the thread to sleap
Thread.sleep(20);
}
// Catch block in there is some
// mishappening while the thread is
// put to sleep
catch (InterruptedException e) {
}
}
}
}
输出:
This is a snapshot captured from front camera where the code is compiled and run. It will differ with realtime basic what comes in front of front camera when the above same code is compiled and run again.