想要在特定目录

时间:2017-06-13 06:30:20

标签: 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.");
}
} 

我的complate代码更改

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                   
}

3 个答案:

答案 0 :(得分:1)

  

如何创建自动快照图像名称和图像保存在特定位置,如Windows临时文件夹?

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在这种情况下)。
  3. 示例输出:

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

    顺便说一句,该部分可能适用于命令行应用程序。建议您的问题与Swing无关 - 所以不要添加Swing标记。

答案 1 :(得分:0)

我只是使用唯一文件名的时间戳和imwrite()函数将图像写入临时文件夹。

这样的事情:

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    ////////////////snapshot button
    int returnVal = jFileChooser1.showSaveDialog(this);

    String path = "THE PATH TO THE TEMP FOLDER";

    // Use java.util.Date
    String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
    String pathToWrite = path + timeStamp + ".jpg";
    Imgcodecs.imwrite(pathToWrite, frame);
} 

答案 2 :(得分:0)

 String path = "C:\\Users\\shan\\Desktop\\photo\\";
       String name = String.format("snapshot-%1s.jpg", System.currentTimeMillis());
      File file = new File(path + name); 
         System.out.print(file);
            Highgui.imwrite(file.getPath(), frame);