java - 想要将视频快照保存在特定目录中

标签 java file opencv webcam temp

对于视频快照保存,我使用 OpenCV lib 和 JFileChooser。目前,当单击快照按钮时,只需打开文件选择器目录,然后写入文件名并选择保存位置,然后保存图像。但现在我想在单击快照按钮创建自动快照图像名称和图像保存特定位置(例如 Windows 临时文件夹)后进行更改。

如何创建自动快照图像名称并将图像保存在特定位置(例如 Windows 临时文件夹)?

快照按钮代码为:

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    ////////////////snapshot button
    int returnVal = jFileChooser1.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = jFileChooser1.getSelectedFile(); //get the path from save dailog
    Highgui.imwrite(file.getPath(), frame);// save frame image to this location
} else {
    System.out.println("File access cancelled by user.");
}
} 

我的更改代码

package gui;
import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.highgui.Highgui;
import org.opencv.highgui.VideoCapture;

/**
 *
 * @author shamim
 */
public class Snapdhot extends javax.swing.JFrame {

// definitions
 private DaemonThread myThread = null;
    int count = 0;
    VideoCapture webSource = null;

    Mat frame = new Mat();
    MatOfByte mem = new MatOfByte();
    
      class DaemonThread implements Runnable
    {
    protected volatile boolean runnable = false;

    @Override
    public  void run()
    {
        synchronized(this)
        {
            while(runnable)
            {
                if(webSource.grab())
                {
                try
                        {
                            webSource.retrieve(frame);
                Highgui.imencode(".bmp", frame, mem);
                Image im = ImageIO.read(new ByteArrayInputStream(mem.toArray()));

                BufferedImage buff = (BufferedImage) im;
                Graphics g=jPanel1.getGraphics();

                if (g.drawImage(buff, 0, 0, getWidth(), getHeight() -150 , 0, 0, buff.getWidth(), buff.getHeight(), null))
                
                if(runnable == false)
                            {
                    System.out.println("Going to wait()");
                    this.wait();
                }
             }
             catch(Exception ex)
                         {
                System.out.println("Error");
                         }
                }
            }
        }
     }
   }
    public Snapdhot() {
        initComponents();
    }

    /**
     * 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")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 570, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 386, Short.MAX_VALUE)
        );

        jButton1.setText("Start");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("pause");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Take Snapshort");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(64, 64, 64)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(127, 127, 127)
                .addComponent(jButton3)
                .addGap(111, 111, 111))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       /// start button 
 webSource =new VideoCapture(0);//video capcher from default cam
  myThread = new DaemonThread();
            Thread t = new Thread(myThread);
            t.setDaemon(true);
            myThread.runnable = true;
            t.start(); // start thard of capcharing
             jButton1.setEnabled(false);  //start button
            jButton2.setEnabled(true);  // stop button
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        
        /// stop button 
myThread.runnable = false; //stop thard
            jButton2.setEnabled(false);   
            jButton1.setEnabled(true);
            
            webSource.release(); // stop capcharing
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        
        ////////////////snapshot button
// 
        //File file = new File("/Documents/fesult.jpg");
//        int returnVal = jFileChooser1.showSaveDialog(this);
//        if (returnVal == JFileChooser.APPROVE_OPTION) {
//        File file = jFileChooser1.getSelectedFile(); //get the path from save dailog
//        Highgui.imwrite(file.getPath(), frame);// save frame image to this location
//        file = new File("/Documents/fesult.jpg");
//    
//        
//        
//        
//    } else {
//        System.out.println("File access cancelled by user.");
//    }
        
       int returnVal = jFileChooser1.showSaveDialog(this);
        String path = System.getProperty("java.io.tmpdir");
        String timeStamp = new SimpleDateFormat().format(new Date());
        String pathToWrite = path + timeStamp + ".jpg";
        Highgui.imwrite(pathToWrite, frame);
    }                                        

    /**
     * @param args the command line arguments
     */

    public static void main(String args[]) {
        
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        /* Create and display the form */
       java.awt.EventQueue.invokeLater(new Runnable() {
       
            @Override
            public void run() {
             new Snapdhot().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}

最佳答案

How to create auto snapshot image name and image save on particular location like windows temp folder?

File f = new File(
        System.getProperty("java.io.tmpdir"), 
        String.format("snapshot-%1s.png", System.currentTimeMillis()));
System.out.println(f);
// Continue to save the image in the file 'f'.

File f = new File(之后,我们有一个文件的两个参数构造函数。本例中的两个参数:

  1. System.getProperty("java.io.tmpdir") 用户的临时目录。
  2. String.format("snapshot-%1s.png", System.currentTimeMillis())); 该名称 snapshot- 后跟当前时间(以毫秒为单位)(以防止多个图像相互覆盖),后跟 . 和文件扩展名(在本例中假定为 png)。

示例输出:

C:\Users\Andrew\AppData\Local\Temp\snapshot-1497342406054.png

顺便说一句,该部分可能适用于命令行应用程序。这表明您的问题与 Swing 无关 - 因此不要添加 Swing 标签。

关于java - 想要将视频快照保存在特定目录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44513860/

相关文章:

java - 具有多个 View 的 Android 触摸事件

algorithm - Intel hex 文件中任意大小的填充模式

c++ - opencv将一个矩阵复制到另一个矩阵的第一列

Java 不会在不包含 main 的不同类中打印

java - docx4j - 删除 wml P 元素

jquery - 如何使用 jQuery 从文件输入中捕获文件名?

java - 无法使用 PrintWriter 在文件中写入

python - 删除图像的上角部分

opencv - 在SGX-Enclave项目中添加OpenCV库

java - 英雄联盟通过其RESTful API阅读 block /关键帧