Showing posts with label writing and reading an image in java. Show all posts
Showing posts with label writing and reading an image in java. Show all posts

June 13, 2014

Security system :Motion Detection System in java

Motion detection system in java : alert when any one pass before system camera

Description : This is a small example for security system in java which send alert through mail and sound while any trespassers pass before your camera connected to system (computer). The program is developed in java media framework. You need jmf.jar and mds.jar to run that code. For sending mail using java mail service application you need to download mail.jar file. The project consist of only 3 packages. Only you have to do is to create a java application in eclipse. copy and paste the following code to your project. compile it and run. Make sure you had added all the jar files to your project. Create a javasecurityalert wave file. Please provide your feed back through comments. Please rate the post.



MainFrame.java
package com.mds.frames;
import java.awt.Container;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import com.mds.serv.AePlayWave;
import com.mds.serv.AlarmSound;
import com.mds.serv.ImageCompare;
import com.mds.serv.MDSMailer;
import com.mds.serv.SwingCapture;
public class MainFrame extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
    private java.awt.Container c = null;
    private com.mds.serv.SwingCapture sc = null;
    private JPanel videoPanel = null;
    private Image refImg = null;
    private Image currentImg = null;
    private File saveImgDir = null;
    private ImageCompare imc = null;
    private AlarmSound as = null;
    private static boolean alarm = true;
    private AePlayWave playWave = null;
    private Thread t2 = null;
    private Thread t1 = null;
    private JButton captureButton = null;
    private static int num = 0;
    private File saveCaptureDir = null;
    private Thread t3 = null;
    private JButton imgSet = null;
    private JButton start = null;
    private JFileChooser jf = null;
    private Thread mainThread = null;
    private JButton stop = null;
   /**
     * This is the default constructor
     */
    public MainFrame() {
        super();
        initialize();
    }
  /**
     * This method initializes this
     *
     * @return void
     */
    private void initialize() {
        this.setSize(900, 550);
        this.setContentPane(getContainer());
        this.setTitle("Motion Detection System");
        this.addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent e)
            {
//                playerclose();
                System.exit(0);
            }
        });
      
    }
  
    private Container getContainer()
    {
        c = new Container();
       imgSet = new JButton();
        imgSet.setText("Set Reference Image");
        imgSet.setBounds(680,180,200,25);
        imgSet.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                videoPanel.setEnabled(true);
                refImg = sc.imageCapture();
//                sc.saveJPG(refImg, s)
            }
        });
        c.add(imgSet);
      
        jf = new JFileChooser();
        start = new JButton("Start Detection");
        start.setBounds(680,230,200,25);
        start.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                saveImgDir = chooseSaveImgDir().getParentFile();
                if(refImg!=null)
                {
                    if(mainThread == null)
                    {
                        startNewThread();
//                        System.out.println("MainThread Started");
                    }
                    else if(mainThread.isAlive())
                        mainThread.resume();
                }
                else
                    showDialog("Set Reference Image");
              
            }
        });
        c.add(start);
      
        stop = new JButton("Stop");
        stop.setBounds(680,280,200,25);
        stop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                try {
                  
//                    if(mainThread == null)
                    if(mainThread.isAlive())
                        mainThread.suspend();
                  
                } catch(NullPointerException e1) {
                    showDialog("Detection Not Started Yet");
                }
              
            }
        });
        c.add(stop);
      
        sc = new SwingCapture();
        videoPanel = sc.getPlayerPanel();
        videoPanel.setEnabled(false);
        c.add(videoPanel);

        playWave = new AePlayWave("alarm.wav");
        t2 = new Thread(playWave);
          
      
        try {
            Thread.sleep(10000);
//            refImg = sc.imageCapture();
//            sc.saveJPG(currentImg, "D:\\Backups\\Saved\\img.jpg");
//            sc.saveJPG(refImg, "c:\\RefImg.jpg");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
      
        captureButton = new JButton();
        captureButton.setText("Capture Frame");
        captureButton.setBounds(680,330,200,25);
        captureButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e)
                {
                    saveCaptureDir = chooseSaveImgDir();
                    System.out.println(saveCaptureDir.getAbsolutePath()+saveCaptureDir.getName());
//                    if(!saveCaptureDir.exists())
//                        saveCaptureDir.mkdirs();
                    SwingCapture.saveJPG(sc.imageCapture(),saveCaptureDir.getAbsolutePath());
                    num++;
                }
          
        });
        c.add(captureButton);      
        return c;
      
    }
  
    private void startNewThread()
    {
        mainThread = new Thread(this);
        mainThread.start();
    }
  
    private void showDialog(String message)
    {
        JOptionPane.showMessageDialog(this, message);
    }
  
    private File chooseSaveImgDir()
    {
        File file = null;
        if(jf.showSaveDialog(this)==JFileChooser.APPROVE_OPTION)
        {
            file = jf.getSelectedFile();
//            System.out.println(saveImgDir.getName());
        }
        return file;

    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        int i =0;
//        saveImgDir = new File("D:\\Backups\\Saved");
        if(saveImgDir==null)
        {
            chooseSaveImgDir();
        }
//        if(!saveImgDir.exists())
//            saveImgDir.mkdirs();
        while(true)
        {
            try {
//                Thread.sleep(250);
                currentImg = sc.imageCapture();
                imc = new ImageCompare(refImg,currentImg);
//                t3 = new Thread(imc);
//                t3.run();
                if(!imc.compare())
                {
                  
                    System.out.println("hi");
                    t2.run();
                    SwingCapture.saveJPG(currentImg, saveImgDir+"\\img"+i+".jpg");
                    MDSMailer m = new MDSMailer(saveImgDir+"\\img"+i+".jpg");
                    t3 = new Thread(m);
                    t3.start();
                    refImg = currentImg;
                }
              
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            i++;
        }
    }

  
    public static void main(String[] args) {
      
        MainFrame m = new MainFrame();
        m.setVisible(true);
//        Thread t = new Thread(m);
//        t.start();
    }
  

}

-------------------------------------
LoginFrame.java


package com.mds.frames;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
public class LoginFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;
    private JLabel NameLabel = null;
    private JLabel PassLabel = null;
    private JTextField NameTextField = null;
    private JPasswordField PasswordField = null;
    private JButton LoginButton = null;
    private JButton ClearButton = null;
    /**
     * This is the default constructor
     */
    public LoginFrame() {
        super();
        initialize();
    }
    /**
     * This method initializes this
     *
     * @return void
     */
    private void initialize() {
        this.setSize(500, 400);
        this.setContentPane(getJContentPane());
       
        this.setTitle("Login");
    }
    /**
     * This method initializes jContentPane
     *
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            PassLabel = new JLabel();
            PassLabel.setBounds(new Rectangle(75, 170, 100, 30));
            PassLabel.setText("Password : ");
            NameLabel = new JLabel();
            NameLabel.setBounds(new Rectangle(75, 120, 100, 30));
            NameLabel.setText("Name : ");
            jContentPane = new JPanel();
            jContentPane.setLayout(null);
            jContentPane.add(NameLabel, null);
            jContentPane.add(PassLabel, null);
            jContentPane.add(getNameTextField(), null);
            jContentPane.add(getPasswordField(), null);
            jContentPane.add(getLoginButton(), null);
            jContentPane.add(getClearButton(), null);
           
        }
        return jContentPane;
    }
    /**
     * This method initializes NameTextField   
     *    
     * @return javax.swing.JTextField   
     */
    private JTextField getNameTextField() {
        if (NameTextField == null) {
            NameTextField = new JTextField();
            NameTextField.setBounds(new Rectangle(225, 120, 180, 30));
        }
        return NameTextField;
    }
    /**
     * This method initializes PasswordField   
     *    
     * @return javax.swing.JPasswordField   
     */
    private JPasswordField getPasswordField() {
        if (PasswordField == null) {
            PasswordField = new JPasswordField();
            PasswordField.setBounds(new Rectangle(225, 170, 180, 30));
        }
        return PasswordField;
    }
    /**
     * This method initializes LoginButton   
     *    
     * @return javax.swing.JButton   
     */
    private JButton getLoginButton() {
        if (LoginButton == null) {
            LoginButton = new JButton();
            LoginButton.setBounds(new Rectangle(140, 230, 80, 25));
            LoginButton.setText("Login");
            LoginButton.addActionListener(new ActionListener () {
                public void actionPerformed(ActionEvent e) {
                   
                   
                    if(NameTextField.getText().compareTo("admin")==0)
                    {
//                        System.out.println("clicked");
                        if(String.valueOf(PasswordField.getPassword()).equals("mds"))
                        {
                       
                            MainFrame m = new MainFrame();
//                            m.setBounds(0,0,900,600);
                            m.setVisible(true);
                            closeWindow();
                        }
                        else
                            showMessageDialog("Invalid Username or Password");
                    }
               
                }
            });
        }
        return LoginButton;
    }
   
    private void showMessageDialog(String message)
    {
        JOptionPane.showMessageDialog(this, message);
    }
   
    private void closeWindow()
    {
        setVisible(false);
        dispose();
    }
   

    /**
     * This method initializes ClearButton   
     *    
     * @return javax.swing.JButton   
     */
    private JButton getClearButton() {
        if (ClearButton == null) {
            ClearButton = new JButton();
            ClearButton.setBounds(new Rectangle(240, 230, 80, 25));
            ClearButton.setText("Clear");
            ClearButton.addActionListener(new ActionListener () {
                public void actionPerformed(ActionEvent e) {
                    NameTextField.setText("");
                    PasswordField.setText("");
                }
            });
        }
       
        return ClearButton;
    }
   
    public static void main(String[] args) {
       
        LoginFrame l = new LoginFrame();
        l.setVisible(true);
    }}

-------------------

January 09, 2013

Image comparison in java using RGB value


How to compare (RGB value) two images using java


This example helps you to compare two images (either jpeg or png) using pixel. first the program check whether two images are of equal breadth and width, then it compare each pixel by pixel and return the output. The program will check whether the two images given resembles each other or not. This is one of the simplest way and pixel based.


package image.analysis.comparison;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/*
*  Image comparison done here is using pixels
*
*/

public class ImageComparison {
   
   
    public boolean compareTwoImages(File fileOne, File  fileTwo) {
        Boolean isTrue = true;
        try{
            Image imgOne = ImageIO.read(fileOne);
            Image imgTwo = ImageIO.read(fileTwo);
            BufferedImage bufImgOne = ImageIO.read(fileOne);
            BufferedImage bufImgTwo = ImageIO.read(fileTwo);
            int imgOneHt = bufImgOne.getHeight();
            int imgTwoHt = bufImgTwo.getHeight();
            int imgOneWt = bufImgOne.getWidth();
            int imgTwoWt = bufImgTwo.getWidth();
            if(imgOneHt!=imgTwoHt ||(imgOneWt!=imgTwoWt)){
                System.out.println(" size are not equal ");
                isTrue = false;
            }
            for(int x =0; x< imgOneHt; x++ ){
                for(int y =0; y <imgOneWt ; y++){
                    if(bufImgOne.getRGB(x, y) != bufImgTwo.getRGB(x, y) ){
                        System.out.println(" size are not equal ");
                        isTrue = false;
                        break;
                    }
                }
            }
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return isTrue;
    }
   
   
    public static void main(String[] args) {
       
        File f = new File("E:\\javaaptitude\\Oracle.jpeg");
        File f2 = new File("E:\\javaaptitude\\Capgemini.jpeg");
        ImageComparison imgComp = new ImageComparison();
        System.out.println(imgComp.compareTwoImages(f, f2));
       
    }
   

}


The above code is for image having same width and height, if the image height and width is different use this code


package Bluetick;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;


public class ImageComparison {
  
  
    public boolean compareTwoImages(File fileOne, File  fileTwo) {
        Boolean isTrue = true;
        try{
            Image imgOne = ImageIO.read(fileOne);
            Image imgTwo = ImageIO.read(fileTwo);
            BufferedImage bufImgOne = ImageIO.read(fileOne);
            BufferedImage bufImgTwo = ImageIO.read(fileTwo);
            int imgOneHt = bufImgOne.getHeight();
            int imgTwoHt = bufImgTwo.getHeight();
            int imgOneWt = bufImgOne.getWidth();
            int imgTwoWt = bufImgTwo.getWidth();
            if(imgOneHt!=imgTwoHt ||(imgOneWt!=imgTwoWt)){
                System.out.println(" size are not equal ");
                isTrue = false;
            }

            for(int x =0; x < imgOneWt; x++ ){ //replace the loop, if needed
                for(int y =0; y < imgOneHt ; y++){
                    if(bufImgOne.getRGB(x, y) != bufImgTwo.getRGB(x, y) ){
                        System.out.println(" rgb are not equal ");
                        isTrue = false;
                        break;
                    }
                }
            }
        }catch (IOException e) {
                        e.printStackTrace();
        }
        return isTrue;
    }
  
  
    public static void main(String[] softwareEngineer) {
      
        File OracleJava = new File("C:\\Image\FingerPrint\analysis.jpg");
        File javaOracle = new File("C:\\Histogram\match\image.jpg");
        ImageComparison imgComp = new ImageComparison();
        System.out.println(imgComp.compareTwoImages( OracleJava , javaOracle));
      
    }
  

}

from comments :-

To work the above code for different dimensional images the for loop has to replaced.

Change the for loop to the following .... for(int x =0; x < imgOneWt; x++ ){ for(int y =0; y < imgOneHt ; y++){ if(bufImgOne.getRGB(x, y) != bufImgTwo.getRGB(x, y) ){ System.out.println(" size are not equal "); isTrue = false; break; } } }


Hope you had tried the above code. Read this for to know how to create a captcha image in java : java be lazy

Thanks all for your valuable feed backs,

+jerin v george





http://javabelazy.blogspot.in/

April 05, 2012

reCAPTCHA is a free




reCAPTCHA: The FREE anti-bot service that helps digitize books

reCAPTCHA is a free CAPTCHA service that protects your site against spam, malicious registrations and other forms of attacks where computers try to disguise themselves as a human;


link :: https://developers.google.com/recaptcha/

Using recaptcha with jsp/java

How to use recaptcha4j api


January 30, 2012

Image reading and writting in java

Reading and writing an image file in java

Last day I want to copy some images from my digital camera to another ones, i copied all the images to that cameras memory card. Both the camera is of different companies, the camera is not displaying any images that i copied, i checked the folders are the same , its not because of the folder. then i noticed the images name, one is number while other is alpha numeric name, Since i had a 1000 of images to copy, renaming one by one seems to be very difficult for me and it will take around hours to complete the renaming process. What i did is i wrote a java program that rename each picture and save to another folder. The program was successful, now the image start displaying in that camera. Here is the program........

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.imageio.ImageIO;



public class RenameImageFiles {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
File f = new File("E:\\belazy");
System.out.println(f.list());
File [] list = f.listFiles();
System.out.println(list.length);
int num = 400;
for ( int i =0 ; i
String fileName = "PICT0"+num+".JPG";
System.out.println(list[i]);
BufferedImage bi = ImageIO.read(list[i]);
System.out.println(fileName+" .. "+ImageIO.write(bi, "JPG" ,new File("D:\\blazyjava\\"+fileName)));
num = num + 1;
}

}

}


Facebook comments