Search code examples
javafileopencvwebcamtemp

Want to save video snapshot in particular directory


For video snapshot save, I use OpenCV lib and JFileChooser. Currently when click on snapshot button just open file chooser directory and then write the file name and select the location for Save and then save the image. But now I want to change something after click snapshot button create auto snapshot image name and image save particular location like windows temp folder.

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

Snapshot button code is:

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

my complate code with change

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                   
}

Solution

  • 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'.
    

    After File f = new File( we have the two argument constructor for a file. The two arguments in this case:

    1. System.getProperty("java.io.tmpdir") The user's temp directory.
    2. String.format("snapshot-%1s.png", System.currentTimeMillis())); That name snapshot- followed by the current time in milliseconds (to prevent multiple images overwriting each other) followed by the . and a file extension (presuming png in this case).

    Example output:

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

    As an aside, that part might apply to a command line app., suggesting your question has nothing to do with Swing - so don't add the Swing tag.