Webcam

Webcam.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package webcam;

// import library
import JImage.JIResizeImage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Panel;
import java.awt.image.BufferedImage;
import java.beans.Encoder;
import java.io.FileOutputStream;
import java.util.Calendar;
import javax.media.Buffer;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author Opay
 */

public class Webcam extends javax.swing.JFrame {
    // Tahap 1 Inisalisasi     
    public Buffer buffer = null;
    public BufferToImage bufferimg = null;
    JFileChooser pilihfile;
    public ImagePanel panel = null;
    String lokasisimpan = "E:\\";
    public int nocapture = 0;
    public Player player;
    public Image img = null;
    
    
    /**
     * Creates new form Webcam
     */
    public Webcam() {
        initComponents();
        setTitle("Capture Webcam v.0.0.1");
        // Tahap 4 Panggil method menyalakan kamera
        hidupkan_kamera();
    }
     
    // Tahap 2 Buat Rancangan Ukuran Tampilan
    public class ImagePanel extends Panel {
        public java.awt.Image picture = null;
        public ImagePanel() {            
            setSize(300, 200);
        }

        public void setImage(java.awt.Image img) {
            this.picture = img;
            repaint();
        }
         @Override
        public void paint(Graphics grafik) {
            if (img != null) {
                grafik.drawImage(img, 0, 0, this);
            }
        }
    }
    
    // Tahap 3 Buat method menyalakan kamera, method capture, dan method simpan file
    public void hidupkan_kamera() {
        pilihfile = new JFileChooser();
        panel = new ImagePanel();
        //String mediaCamera = "vfw:Microsoft WDM Image Capture (Win32):0";
        String mediaCamera = "vfw://0";
        layar1.setLayout(new BorderLayout());
        layar2.setLayout(new BorderLayout());

        try {
            MediaLocator mediaLocator = new MediaLocator(mediaCamera);
            player = Manager.createRealizedPlayer(mediaLocator);
            if (player.getVisualComponent() != null) {                
                player.getVisualComponent().setSize(300, 200);                
                layar1.add(player.getVisualComponent());
            }
            layar2.add(panel);
            player.start();

        } catch (Exception e) {
            System.err.println("Salah" + e);
        }
    }

    public void capture() {
        FrameGrabbingControl frmgarcon = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
        buffer = frmgarcon.grabFrame();
        bufferimg = new BufferToImage((VideoFormat) buffer.getFormat());
        img = bufferimg.createImage(buffer);
        //JIResizeImage resize = new JIResizeImage();
        //BufferedImage BI = (BufferedImage) img;
        //java.awt.Image img2 = resize.rescale(BI, 300, 200);
        //panel.setImage(img2);
        // 
        JIResizeImage resize = new JIResizeImage();
        BufferedImage BI = (BufferedImage) img;
        Image img = resize.rescale(BI, 33);
        panel.setImage(img);

        Calendar waktu = Calendar.getInstance();
        int date = (waktu.getTime().getYear() + 1900) * 10000 + (waktu.getTime().getMonth() + 1) * 100 + waktu.getTime().getDate();
        simpanfile(img, lokasisimpan + date + nocapture + ".jpg");
        nocapture++;
    }

    private void simpanfile(java.awt.Image image, String s) {
        BufferedImage bufferedimage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D grafik2d = bufferedimage.createGraphics();
        grafik2d.drawImage(img, null, null);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(s);
        } catch (java.io.FileNotFoundException ex) {
            ex.printStackTrace();
        }
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedimage);
        param.setQuality(0.5f, false);
        encoder.setJPEGEncodeParam(param);
        try {
            encoder.encode(bufferedimage);
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    

    /**
     * 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() {

        layar1 = new javax.swing.JLabel();
        layar2 = new javax.swing.JLabel();
        Rekam = new javax.swing.JButton();
        Judul = new javax.swing.JLabel();
        Modifikasi = new javax.swing.JLabel();
        Nama = new javax.swing.JLabel();
        Nim = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        layar1.setBackground(new java.awt.Color(255, 255, 255));

        Rekam.setBackground(new java.awt.Color(0, 153, 153));
        Rekam.setText("Capture");
        Rekam.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RekamActionPerformed(evt);
            }
        });

        Judul.setText("CapCam v.0.0.1");

        Modifikasi.setText("Dimodifikasi Oleh");

        Nama.setText("Taupik Nurhidayat");

        Nim.setText("49013105");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(layar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(layar2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(Rekam)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(Judul)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(Modifikasi)
                                    .addComponent(Nama)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(33, 33, 33)
                                .addComponent(Nim)))
                        .addContainerGap(22, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(layar1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(layar2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(Rekam, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(Judul)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Modifikasi)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Nama)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Nim)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

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

    // Tahap 5 Buat aksi tombol
    private void RekamActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
        capture();
    }                                     

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Webcam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Webcam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Webcam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Webcam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Webcam().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel Judul;
    private javax.swing.JLabel Modifikasi;
    private javax.swing.JLabel Nama;
    private javax.swing.JLabel Nim;
    private javax.swing.JButton Rekam;
    private javax.swing.JLabel layar1;
    private javax.swing.JLabel layar2;
    // End of variables declaration                   
  
}

Library yang digunakan
1. JImage_.jar
2. jmf.jar
3. rt.jar

Direktori Simpan
webcam

Video Aplikasinya

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s