Showing posts with label image. Show all posts
Showing posts with label image. Show all posts

Friday, November 16, 2018

Spoofing file extensions on HackerOne

While testing HackerOne, I observed an issue with the file upload functionality. It seems that on File upload, the uploader uses the content within the file for determining the content type of file instead of filetype .

Although this does not pose much of a risk since the changed extensions would be visible at download time but wanted to blog about this.

This raises below 2 scenario:

Scenario 1


  • Open the batch.cmd on the posted comment
  • Observe an image gets represented and their is no warning from HackerOne

  • User downloads the file, thinking of it as an image file 
  • if the user accidentally ignores the downloaded file extensions opens it then malicious batch file gets executed



Scenario 2 


  • Open the myFile.txt on the posted comment
  • You will see a warning from Hackerone, but since the file is txt file so user might just go ahead 

  • User downloads the file, thinking of it as an text file

  • if the user accidentally ignores the downloaded file extensions opens it then malicious HTML scripts execute


Reason:

  1. Content-Disposition: attachment; filename="" in response from hackerone-attachments.s3.amazonaws.com does not contain filename, forcing browser to decide the naming convention. 
  2. Since the Content type got decided on basis of file content header instead of extension by HackerOne so few browser would simply save it on user computer with incorrect extension, which caused the above Scenarios 1 and 2
HackerOne Report:
https://hackerone.com/reports/268123 (Closed as Informative)

Sunday, July 23, 2017

Facial Detection using Java

In this post, we will learn how to extract faces out of an image from webcam. We will make use of 2 library which are sarxos and openimaj

Language Used:
Java

Git Repo:
https://github.com/csanuragjain/extra/tree/master/FaceRecognition

Website:
https://cooltrickshome.blogspot.com/2017/07/facial-recognition-using-java.html

Pom Dependency:
 <dependency>  
   <groupId>org.openimaj</groupId>  
   <artifactId>image-feature-extraction</artifactId>  
   <version>1.3.5</version>  
 </dependency>  
 <dependency>  
      <artifactId>faces</artifactId>  
      <groupId>org.openimaj</groupId>  
      <version>1.3.5</version>  
      <scope>compile</scope>  
 </dependency>  
 <dependency>  
        <groupId>com.github.sarxos</groupId>  
        <artifactId>webcam-capture</artifactId>  
        <version>0.3.11</version>  
        <scope>test</scope>  
   </dependency>  

Reference:
https://cooltrickshome.blogspot.com/2016/11/take-snapshot-from-webcam-using-java-in.html
http://openimaj.org/

Program:

FaceDetector.java

Variables:
      private static final long serialVersionUID = 1L;  
      private static final HaarCascadeDetector detector = new HaarCascadeDetector();  
      private Webcam webcam = null;  
      private BufferedImage img= null;  
      private List<DetectedFace> faces = null;  


main method:
 public static void main(String[] args) throws IOException {  
           new FaceDetector().detectFace();  
      }  

How it works:
1) We create an object of FaceDetector class which class the default constructor and then we call the detectFace method of this class.

FaceDetector constructor:
      public FaceDetector() throws IOException {  
           webcam = Webcam.getDefault();  
           webcam.setViewSize(WebcamResolution.VGA.getSize());  
           webcam.open(true);  
           img=webcam.getImage();  
           webcam.close();  
           ImagePanel panel=new ImagePanel(img);  
           panel.setPreferredSize(WebcamResolution.VGA.getSize());  
           add(panel);  
           setTitle("Face Recognizer");  
           setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
           pack();  
           setLocationRelativeTo(null);  
           setVisible(true);  
      }  

How it works:
1) We use the sarxos library for webcam here
2) We create a webcam object and set the viewsize
3) We open the webcam using the open method
4) We take the image from webcam and store it into a BufferedImage object named img
5) Now we close the webcam and pass the image obtained in ImagePanel class which would then be added to Frame.
6) Now we show the frame to user with the webcam image which will be processed.

detectFace method:
      public void detectFace(){  
           JFrame fr=new JFrame("Discovered Faces");  
           faces = detector.detectFaces(ImageUtilities.createFImage(img));  
           if (faces == null) {  
                System.out.println("No faces found in the captured image");  
                return;  
           }  
           Iterator<DetectedFace> dfi = faces.iterator();  
           while (dfi.hasNext()) {  
                DetectedFace face = dfi.next();  
                FImage image1 = face.getFacePatch();  
                ImagePanel p=new ImagePanel(ImageUtilities.createBufferedImage(image1));  
                fr.add(p);  
           }  
           fr.setLayout(new FlowLayout(0));  
           fr.setSize(500,500);  
           fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
           fr.setVisible(true);  
      }  

How it works:
1) We use the openimaj library for face detection
2) We create a new Frame which would be showing up the results.
3) We make use of detectFaces method of HaarCascadeDetector class object detector, passing the image to be processed. ImageUtilities is used to create FImage out of BufferedImage.
4) If no face is found on image then an error message is returned.
5) Otherwise, we iterate through each face and retrieve the faces using getFacePatch method.
6) Again we use the createBufferedImage method of ImageUtilities class to get a BufferedImage out of FImage.
7) We add all the faces to the resulting frame.

ImagePanel Class:
 package com.cooltrickshome;  
 import java.awt.Dimension;  
 import java.awt.Graphics;  
 import java.awt.Image;  
 import javax.swing.ImageIcon;  
 import javax.swing.JPanel;  
 class ImagePanel  
  extends JPanel  
 {  
  private Image img;  
  public ImagePanel(String img)  
  {  
   this(new ImageIcon(img).getImage());  
  }  
  public ImagePanel(Image img)  
  {  
   this.img = img;  
   Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));  
   setPreferredSize(size);  
   setMinimumSize(size);  
   setMaximumSize(size);  
   setSize(size);  
   setLayout(null);  
  }  
  public void paintComponent(Graphics g)  
  {  
   g.drawImage(this.img, 0, 0, null);  
  }  
 }  

How it works:
1) This is used to show the image over a panel

Output:


Full Program:


FaceDetector.java
 package com.cooltrickshome;  
 /**  
  * Reference:  
  * https://github.com/sarxos/webcam-capture/tree/master/webcam-capture-examples/webcam-capture-detect-face  
  * http://openimaj.org/  
  */  
 import java.awt.FlowLayout;  
 import java.awt.image.BufferedImage;  
 import java.io.IOException;  
 import java.util.Iterator;  
 import java.util.List;  
 import javax.swing.JFrame;  
 import org.openimaj.image.FImage;  
 import org.openimaj.image.ImageUtilities;  
 import org.openimaj.image.processing.face.detection.DetectedFace;  
 import org.openimaj.image.processing.face.detection.HaarCascadeDetector;  
 import com.github.sarxos.webcam.Webcam;  
 import com.github.sarxos.webcam.WebcamResolution;  
 public class FaceDetector extends JFrame {  
      private static final long serialVersionUID = 1L;  
      private static final HaarCascadeDetector detector = new HaarCascadeDetector();  
      private Webcam webcam = null;  
      private BufferedImage img= null;  
      private List<DetectedFace> faces = null;  
      public FaceDetector() throws IOException {  
           webcam = Webcam.getDefault();  
           webcam.setViewSize(WebcamResolution.VGA.getSize());  
           webcam.open(true);  
           img=webcam.getImage();  
           webcam.close();  
           ImagePanel panel=new ImagePanel(img);  
           panel.setPreferredSize(WebcamResolution.VGA.getSize());  
           add(panel);  
           setTitle("Face Recognizer");  
           setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
           pack();  
           setLocationRelativeTo(null);  
           setVisible(true);  
      }  
      public void detectFace(){  
           JFrame fr=new JFrame("Discovered Faces");  
           faces = detector.detectFaces(ImageUtilities.createFImage(img));  
           if (faces == null) {  
                System.out.println("No faces found in the captured image");  
                return;  
           }  
           Iterator<DetectedFace> dfi = faces.iterator();  
           while (dfi.hasNext()) {  
                DetectedFace face = dfi.next();  
                FImage image1 = face.getFacePatch();  
                ImagePanel p=new ImagePanel(ImageUtilities.createBufferedImage(image1));  
                fr.add(p);  
           }  
           fr.setLayout(new FlowLayout(0));  
           fr.setSize(500,500);  
           fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
           fr.setVisible(true);  
      }  
      public static void main(String[] args) throws IOException {  
           new FaceDetector().detectFace();  
      }  
 }  

ImagePanel.java
 package com.cooltrickshome;  
 import java.awt.Dimension;  
 import java.awt.Graphics;  
 import java.awt.Image;  
 import javax.swing.ImageIcon;  
 import javax.swing.JPanel;  
 class ImagePanel  
  extends JPanel  
 {  
  private Image img;  
  public ImagePanel(String img)  
  {  
   this(new ImageIcon(img).getImage());  
  }  
  public ImagePanel(Image img)  
  {  
   this.img = img;  
   Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));  
   setPreferredSize(size);  
   setMinimumSize(size);  
   setMaximumSize(size);  
   setSize(size);  
   setLayout(null);  
  }  
  public void paintComponent(Graphics g)  
  {  
   g.drawImage(this.img, 0, 0, null);  
  }  
 }  

Hope it helps :)

Friday, July 21, 2017

Some Image Based Exploits with their Prevention

Images can be used to run malicious scripts over browser and can also be used to download Trojans if not handled carefully by your website. Too much trust on user input can cause damage to your clients.

In this post, we will run malicious scripts using a simple image viewer functionality and lastly we will discuss on how we can resolve this.

Programming Language
HTML, PHP

Git Repository
https://github.com/csanuragjain/extra/tree/master/ImageExploit

Website
https://cooltrickshome.blogspot.in/2017/07/some-image-based-exploits-with-their.html

One of Image Vulnerability I reported:
https://hackerone.com/reports/221928

Scenario #1:
In this scenario, we will show how lacking Content-Type while displaying images can run malicious scripts.
 Malicious Image




















Description
1)  Right Click on above Image and then Choose Save Image As
2) Name it as exifxss.jpg and Save it.
3) Otherwise you can also get it from the git location.

showImage.php
 <?php  
 include('exifxss.jpg');  
 ?>  


Description
A simple php file which would be showing the above jpg file.

Output:
  1. When you access showImage.php on your browser, you will expect to see the image but instead you will see several pop up coming up.
  2. This happens since the php page is not setting the Content-Type which makes php show image as an HTML. Since Image has several alert messages so they start popping up.
  3. showImage.php need to make sure that it sets the correct Content-Type and also make sure that it does not set the user provided Content-Type.


Scenario #2:
In this scenario, we will show how simple looking image when downloaded can become an exploit.
Caution: This will run notepad, calc, msconfig, services.msc on your computer, although it won't perform anything malicious.

Malicious Image











Description
1)  Right Click on above Image and then Choose Save Image As
2) Name it as exifxss.bat and Save it.
3) Otherwise you can also get it from the git location.

showImage2.html
 <img src="image.bat" width=500 height=500/>  

Description
A simple HTML file showing the image image.bat

Output:

  1. On accessing the above HTML, you would see the bugs bunny image (nothing suspicious)
  2. Now right click on Image and save the image. It would be saved as image.bat
  3. On opening it the malicious payload gets executed opening up notepad, services.msc, msconfig, calc.
  4. To prevent it, make sure that users are never allowed to store any non image extension file.
Please let me know your suggestions and comments.
Hope it helps :)

Saturday, July 8, 2017

Create Image Thumbnails using Java

In this post we will learn how we can utilize java to automatically creates thumbnails for existing images with desired thumbnail scaling.

Programming Language:
Java

Git Location:
https://github.com/csanuragjain/extra/tree/master/ThumbnailGenerator

Tutorial Location:
https://cooltrickshome.blogspot.in/2017/07/create-image-thumbnails-using-java.html

Program:

main method:

1
2
3
4
5
6
7
8
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Scanner s =new Scanner(System.in);
  System.out.println("Enter the path of image whose thumbnail need to be generated");
  String imgPath=s.nextLine();
  File thumnailImg=createThumbnail(new File(imgPath), 400, 400);
  System.out.println("Thumbnail generated at "+thumnailImg.getAbsolutePath());
 }

How it works:
1) A scanner object is created to take user input.
2) Image location for which thumbnail need to be generated is taken using the scanner object
3) We call the createThumbnail function (will create this) passing the image and the required thumbnail width and height.
4) createThumbnail returns the File object pointing to the generated thumbnail which is now shown to user.

createThumbnail method:
 /**
  * Creates a thumnail of provided image
  * @param inputImgFile The input image file
  * @param thumnail_width Desired width of the output thumbnail
  * @param thumbnail_height Desired height of thr output thumnail
  */
 public static File createThumbnail(File inputImgFile, int thumnail_width, int thumbnail_height){
  File outputFile=null;
  try {
  BufferedImage img = new BufferedImage(thumnail_width, thumbnail_height, BufferedImage.TYPE_INT_RGB);
  img.createGraphics().drawImage(ImageIO.read(inputImgFile).getScaledInstance(thumnail_width, thumbnail_height, Image.SCALE_SMOOTH),0,0,null);
  outputFile=new File(inputImgFile.getParentFile()+File.separator+"thumnail_"+inputImgFile.getName());
   ImageIO.write(img, "jpg", outputFile);
   return outputFile;
  } catch (IOException e) {
   System.out.println("Exception while generating thumbnail "+e.getMessage());
   return null;
  }
 }

How it works:
1) We use the ImageIO class to create a scaled version of the input image using the predefined getScaledInstance method passing the desired thumbnail width and height
2) We pass the Image from Step1 into a BufferedImage object
3) Now we simply use the write method of ImageIO class to write the BufferedImage from Step2 into a jpg file and return a File object pointing to same.

Output:
 Enter the path of image whose thumbnail need to be generated  
 C:\images\extra\7.jpg  
 Thumbnail generated at C:\images\extra\thumnail_7.jpg  

Full Program:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.cooltrickshome;

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

import javax.imageio.ImageIO;

public class ThumbnailGenerator {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Scanner s =new Scanner(System.in);
  System.out.println("Enter the path of image whose thumbnail need to be generated");
  String imgPath=s.nextLine();
  File thumnailImg=createThumbnail(new File(imgPath), 400, 400);
  System.out.println("Thumbnail generated at "+thumnailImg.getAbsolutePath());
 }

 /**
  * Creates a thumnail of provided image
  * @param inputImgFile The input image file
  * @param thumnail_width Desired width of the output thumbnail
  * @param thumbnail_height Desired height of thr output thumnail
  */
 public static File createThumbnail(File inputImgFile, int thumnail_width, int thumbnail_height){
  File outputFile=null;
  try {
  BufferedImage img = new BufferedImage(thumnail_width, thumbnail_height, BufferedImage.TYPE_INT_RGB);
  img.createGraphics().drawImage(ImageIO.read(inputImgFile).getScaledInstance(thumnail_width, thumbnail_height, Image.SCALE_SMOOTH),0,0,null);
  outputFile=new File(inputImgFile.getParentFile()+File.separator+"thumnail_"+inputImgFile.getName());
   ImageIO.write(img, "jpg", outputFile);
   return outputFile;
  } catch (IOException e) {
   System.out.println("Exception while generating thumbnail "+e.getMessage());
   return null;
  }
 }
}

Hope it helps :)

Saturday, March 18, 2017

Image to PDF using Java

This blog post will allow you to convert your images from either your local system or from URL into pdf format using java code. This will make use of itextpdf library.

Language Used:
Java

Git Location:
https://github.com/csanuragjain/extra/tree/master/Image2PDF

POM Dependency:
  <dependency>  
       <groupId>com.itextpdf</groupId>  
       <artifactId>itextpdf</artifactId>  
       <version>5.0.6</version>  
       <scope>test</scope>  
  </dependency>  

Program:
main method:
      public static void main(String[] args) {  
           Scanner s =new Scanner(System.in);  
           System.out.println("Please provide the path of image");  
           String imgPath=s.nextLine();  
           System.out.println("Please provide the path of pdf");  
           String pdfPath=s.nextLine();  
           boolean isValidURL=false;  
           URL url;  
           try {  
             url = new URL(imgPath);  
             isValidURL=true;  
           } catch (MalformedURLException e) {  
           }  
           new ImageToPDF().imageToPdf(imgPath, pdfPath, isValidURL);  
           s.close();  
           System.out.println("PDF created...");
      }  

How it works:
  1. We create a scanner object to get user input.
  2. We obtain the source path of image and pdf to be created.
  3. We check if the source path of image is a url or is coming from user local computer. We do this by making a URL class object with the image path passed. If the URL is valid then we update isValidURL to true else false.
  4. Now we call the imagetoPDF method which actually converts the image to pdf.
  5. First argument is the path of image. Second one is the path of pdf. Third argument tell if the image is coming from a URL or from user local computer.
imageToPdf method:
      public void imageToPdf(String imgPath, String pdfPath, boolean isValidURL)  
      {  
           Document document= new Document(PageSize.A4);  
           FileOutputStream fos;  
           try {  
                fos = new FileOutputStream(new File(pdfPath));  
                PdfWriter writer = PdfWriter.getInstance(document, fos);  
                writer.open();  
             document.open();  
             if(isValidURL)  
             {  
                  Image img=Image.getInstance(new java.net.URL(imgPath));  
                  float scaler = ((document.getPageSize().getWidth() - document.leftMargin()  
                   - document.rightMargin()) / img.getWidth()) * 100;  
                  img.scalePercent(scaler);  
                  document.add(img);  
             }  
             else  
             {  
                  Image img=Image.getInstance(imgPath);  
                  float scaler = ((document.getPageSize().getWidth() - document.leftMargin()  
                   - document.rightMargin()) / img.getWidth()) * 100;  
                  img.scalePercent(scaler);  
                  document.add(img);  
             }  
             document.close();  
             writer.close();  
           } catch (FileNotFoundException e) {  
                System.out.println("File not found "+e.getMessage());  
           } catch (DocumentException e) {  
                System.out.println("Document exception "+e.getMessage());  
           } catch (MalformedURLException e) {  
                System.out.println("Incorrect path given "+e.getMessage());  
           } catch (IOException e) {  
                System.out.println("Issue while accessing the input file "+e.getMessage());  
           }  
      }  


How it works:
  1. We make a document object and pass PageSize.A4 which simply tells that resulting pdf has A4 size page.
  2. We create a PDFWriter object passing the document we created in step1 and a FileOutputStream object pointing to the pdf file to be created as argument. PDFWriter will be responsible of actually writing on the pdf.
  3. We open the writer object and document object.
  4. Now we prepare the document by adding the image to it. For this we use the add function on document. 
  5. We resized the image using scalePercent so that image does not become larger than pdf.
  6. We close the document and writer which ultimately completes the process and pdf is created.
Output:
 #1  
 Please provide the path of image  
 screen1.jpg  
 Please provide the path of pdf  
 screen1.pdf  
 PDF created...  
 #2  
 Please provide the path of image  
 https://ul-a.akamaihd.net/images/products/94427/product/Apollo_Infinite_FNSF51APMI30000SAAAA.jpg?1467964020  
 Please provide the path of pdf  
 abc.pdf  
 PDF created...  

Full Program:
 package com.cooltrickshome;  
 import java.io.File;  
 import java.io.FileNotFoundException;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 import java.util.Scanner;  
 import com.itextpdf.text.Document;  
 import com.itextpdf.text.DocumentException;  
 import com.itextpdf.text.Image;  
 import com.itextpdf.text.PageSize;  
 import com.itextpdf.text.pdf.PdfWriter;  
 public class ImageToPDF {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           Scanner s =new Scanner(System.in);  
           System.out.println("Please provide the path of image");  
           String imgPath=s.nextLine();  
           System.out.println("Please provide the path of pdf");  
           String pdfPath=s.nextLine();  
           boolean isValidURL=false;  
           URL url;  
           try {  
             url = new URL(imgPath);  
             isValidURL=true;  
           } catch (MalformedURLException e) {  
           }  
           new ImageToPDF().imageToPdf(imgPath, pdfPath, isValidURL);  
           s.close();  
           System.out.println("PDF created...");  
      }  
      public void imageToPdf(String imgPath, String pdfPath, boolean isValidURL)  
      {  
           Document document= new Document(PageSize.A4);  
           FileOutputStream fos;  
           try {  
                fos = new FileOutputStream(new File(pdfPath));  
                PdfWriter writer = PdfWriter.getInstance(document, fos);  
                writer.open();  
             document.open();  
             if(isValidURL)  
             {  
                  Image img=Image.getInstance(new java.net.URL(imgPath));  
                  float scaler = ((document.getPageSize().getWidth() - document.leftMargin()  
                   - document.rightMargin()) / img.getWidth()) * 100;  
                  img.scalePercent(scaler);  
                  document.add(img);  
             }  
             else  
             {  
                  Image img=Image.getInstance(imgPath);  
                  float scaler = ((document.getPageSize().getWidth() - document.leftMargin()  
                   - document.rightMargin()) / img.getWidth()) * 100;  
                  img.scalePercent(scaler);  
                  document.add(img);  
             }  
             document.close();  
             writer.close();  
           } catch (FileNotFoundException e) {  
                System.out.println("File not found "+e.getMessage());  
           } catch (DocumentException e) {  
                System.out.println("Document exception "+e.getMessage());  
           } catch (MalformedURLException e) {  
                System.out.println("Incorrect path given "+e.getMessage());  
           } catch (IOException e) {  
                System.out.println("Issue while accessing the input file "+e.getMessage());  
           }  
      }  
 }  

Hope it helps :)

Friday, February 17, 2017

Reading text from Images using Java

This post will help read texts from your images. It makes use of tessaract library.
You can also use the below module to check if the captcha on your site is strong enough and cannot be broken simply.

Reference:
https://github.com/tesseract-ocr/tessdata
http://stackoverflow.com/questions/18095708/tess4j-doesnt-use-its-tessdata-folder

Language Used:
Java

Git Location:
https://github.com/csanuragjain/extra/tree/master/ReadFromImages

POM Dependency:
 <!-- https://mvnrepository.com/artifact/net.sourceforge.tess4j/tess4j -->  
 <dependency>  
   <groupId>net.sourceforge.tess4j</groupId>  
   <artifactId>tess4j</artifactId>  
   <version>3.2.1</version>  
 </dependency>  

Pre-requisite:
1) Assume you are running this program from c:\myprogram. Now you can follow either of 2 methods based on your requirements.

Space saving method: (You only download the language data which you need. Only require 30MB for a english dataset)
2) Create a folder named tessdata inside c:\myprogram\
3) Navigate to https://github.com/tesseract-ocr/tessdata
4) Download eng.traineddata for breaking captcha with english language (trained data are available for other languages as well)
5) Place the eng.traineddata inside tessdata folder.
6) Finally your folder structure should look like c:\myprogram\tessdata\eng.traineddata

Time saving method: (Download trained data from several languages and atleast cosumes 1GB space)
7) You can also skip Step 2 to Step 5 and simply download the tessdata-master folder from https://github.com/tesseract-ocr/tessdata
8) Unzip the content of tessdata-master.zip file in your main project folder (for eg here it is c:\myprogram\)
9) Rename tessdata-master to tessdata
10) Finally your folder structure should look like c:\myprogram\tessdata\<Trained data from several language>

Program:

ImageCracker class, crackImage method:
 public static String crackImage(String filePath) {  
     File imageFile = new File(filePath);  
     ITesseract instance = new Tesseract();  
     try {  
       String result = instance.doOCR(imageFile);  
       return result;  
     } catch (TesseractException e) {  
       System.err.println(e.getMessage());  
       return "Error while reading image";  
     }  
   }  

How it works:
1) crackImage takes the image which need to be read
2) We point a file object to that image
3) We make a Tessaract object named instance
4) We call the predefined method doOCR of Tessaract library passing the file object from step2
5) the doOCR method returns the text read from the image and returns the same.
6) In case of failure it prints the error message and returns a error string.

Driver class, main method:
 public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           System.out.println(ImageCracker.crackImage("testImage.PNG"));  
      }  

How it works:
1) We call the crackImage method passing the image to be read from.
2) We print the text read from the method on the console.

Input Image (testImage.PNG):
Output:
Create a Youtube metadata crawler using Java

Full Program:

ImageCracker class
 package com.cooltrickshome;  
 import java.io.File;  
 import net.sourceforge.tess4j.*;  
 public class ImageCracker {  
   public static String crackImage(String filePath) {  
     File imageFile = new File(filePath);  
     ITesseract instance = new Tesseract();   
     try {  
       String result = instance.doOCR(imageFile);  
       return result;  
     } catch (TesseractException e) {  
       System.err.println(e.getMessage());  
       return "Error while reading image";  
     }  
   }  
 }  

Driver class:
 package com.cooltrickshome;  
 public class Driver {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           System.out.println(ImageCracker.crackImage("testImage.PNG"));  
      }  
 }  

Hope it helps :)

Sunday, December 18, 2016

Create your own Free Screen Recorder using Java

Their are many commercial software which allows you to record your desktop screen and save the video.
In this post we will learn how to create a simple screen recorder using Java. This recorder will be capable of recording full screen or record the user selected region.

How it works:
1) When user starts the recording then program starts 2 threads.
2) The first thread keeps on taking screenshot of the screen and saves them into local disk mentioned in variable inputImgDir
3) The second thread continuously looks over the inputImageDir and adds all the new images into the video.
4) When user press stop recording then both threads stop and final video is retrieved.

Language Used:
Java

Git Repo:
https://github.com/csanuragjain/recorder/tree/master/ScreenRecorder

POM Dependency:
Please add the below pom dependency from https://mvnrepository.com/artifact/org.bytedeco/javacv:
<dependency>   
   <groupId>org.bytedeco</groupId>   
   <artifactId>javacv</artifactId>   
   <version>1.0</version>   
  </dependency>  

Reference:
https://cooltrickshome.blogspot.in/2016/11/convert-movie-to-images-using-java.html
https://cooltrickshome.blogspot.in/2016/11/create-desktop-screenshot-maker.html

Program:

Variables:
      public static boolean videoComplete=false;  
      public static String inputImageDir="inputImgFolder"+File.separator;  
      public static String inputImgExt="png";  
      public static String outputVideo="recording.mp4";   
      public static int counter=0;  
      public static int imgProcessed=0;  
      public static FFmpegFrameRecorder recorder=null;  
      public static int videoWidth=1920;  
      public static int videoHeight=1080;  
      public static int videoFrameRate=3;  
      public static int videoQuality=0; // 0 is the max quality  
      public static int videoBitRate=9000;  
      public static String videoFormat="mp4";  
      public static int videoCodec=avcodec.AV_CODEC_ID_MPEG4;  
      public static Thread t1=null;  
      public static Thread t2=null;  
      public static JFrame frame=null;  
      public static boolean isRegionSelected=false;  
      public static int c1=0;  
      public static int c2=0;  
      public static int c3=0;  
      public static int c4=0;  


Explanation:
1) videoComplete variables tells if user has stopped the recording or not.
2) inputImageDir defines the input directory where screenshots will be stored which would be utilized by the video thread
3) inputImgExt denotes the extension of the image taken for screenshot.
4) outputVideo is the name of the recorded video file
5) counter is used for numbering the screenshots when stored in input directory.
6) recorder is used for starting and stopping the video recording
7) videoWidth, videoFrameRate etc define output video param
8) If user wants to record only a selected region then c1,c2,c3,c4 denotes the coordinate

getRecorder method:
      public static FFmpegFrameRecorder getRecorder() throws Exception  
      {  
            if(recorder!=null)  
            {  
                 return recorder;  
            }  
            recorder = new FFmpegFrameRecorder(outputVideo,videoWidth,videoHeight);  
            try  
            {  
            recorder.setFrameRate(videoFrameRate);  
      recorder.setVideoCodec(videoCodec);  
      recorder.setVideoBitrate(videoBitRate);  
      recorder.setFormat(videoFormat);  
      recorder.setVideoQuality(videoQuality); // maximum quality  
      recorder.start();  
            }  
            catch(Exception e)  
            {  
                 JOptionPane.showMessageDialog(frame, "Exception while starting the recorder object "+e.getMessage());  
                 System.out.println("Exception while starting the recorder object "+e.getMessage());  
                 throw new Exception("Unable to start recorder");  
            }  
      return recorder;  
      }  

Explanation:
1) This method is used to get the Recorder object.
2) We create an object of FFmpegFrameRecorder named "Recorder" and then set all its video parameters.
3) Lastly we start the recorder and then return the object.

getRobot method:
      public static Robot getRobot() throws Exception  
      {  
           Robot r=null;  
           try {  
                r = new Robot();  
                return r;  
           } catch (AWTException e) {  
                JOptionPane.showMessageDialog(frame, "Issue while initiating Robot object "+e.getMessage());  
                System.out.println("Issue while initiating Robot object "+e.getMessage());  
                throw new Exception("Issue while initiating Robot object");  
           }  
      }  

Explanation:
1) This method retrieves an object of Robot class which could be further utilized by remaining methods.

main Method:
      public static void main(String[] args) {  
           try {  
                if(getRecorder()==null)  
                {  
                     System.out.println("Cannot make recorder object, Exiting program");  
                     System.exit(0);  
                }  
                if(getRobot()==null)  
                {  
                     System.out.println("Cannot make robot object, Exiting program");  
                     System.exit(0);  
                }  
                File scanFolder=new File(inputImageDir);  
                scanFolder.delete();  
                scanFolder.mkdirs();  
                createGUI();  
           } catch (Exception e) {  
                System.out.println("Exception in program "+e.getMessage());  
           }  
      }  

Explanation:
1) We initialize the recorder and Robot object.
2) We create the input image folder.
3) Now we open up the GUI which will allow user to start/stop the recording.

createGUI method:
      public static void createGUI()  
      {  
           frame=new JFrame("Screen Recorder");  
           JButton b1=new JButton("Select Region for Recording");  
           JButton b2=new JButton("Start Recording");  
           JButton b3=new JButton("Stop Recording");  
           JLabel l1=new JLabel("<html><br/>If you dont select a region then full screen recording <br/> will be made when you click on Start Recording</html>");  
           l1.setFont (l1.getFont ().deriveFont (20.0f));  
           b1.addActionListener(new ActionListener() {  
       @Override  
       public void actionPerformed(ActionEvent e) {  
            try {  
                 JOptionPane.showMessageDialog(frame, "A new window will open. Use your mouse to select the region you like to record");  
                          new CropRegion().getImage();  
                     } catch (Exception e1) {  
                          // TODO Auto-generated catch block  
                          System.out.println("Issue while trying to call the module to crop region");  
                          e1.printStackTrace();  
                     }   
       }  
     });  
           b2.addActionListener(new ActionListener() {  
       @Override  
       public void actionPerformed(ActionEvent e) {  
            counter=0;  
         startRecording();  
       }  
     });  
           b3.addActionListener(new ActionListener() {  
       @Override  
       public void actionPerformed(ActionEvent e) {  
         stopRecording();  
         System.out.print("Exiting...");  
         System.exit(0);  
       }  
     });  
           frame.add(b1);  
           frame.add(b2);  
           frame.add(b3);  
           frame.add(l1);  
           frame.setLayout(new FlowLayout(0));  
           frame.setVisible(true);  
           frame.setSize(1000, 170);  
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
      }  

Explanation:
1) We make a JFrame with the button for staring and stopping the recording. One more button is added for allowing user to record only a selected portion of screen
2) If user clicks to select only certain region then we call a class CropRegion method getImage which helps in retrieving the coordinate of the region selected by user and update the same in variable c1,c2,c3,c4
3) If user clicks on start recording then startRecording method is called
4) If user clicks on stoprecording then stopRecording method is called

startRecording method:
      public static void startRecording()  
      {  
           t1=new Thread()  
           {  
             public void run() {  
               try {  
                          takeScreenshot(getRobot());  
                     } catch (Exception e) {  
                          JOptionPane.showMessageDialog(frame, "Cannot make robot object, Exiting program "+e.getMessage());  
                          System.out.println("Cannot make robot object, Exiting program "+e.getMessage());  
                          System.exit(0);  
                     }  
             }  
           };  
           t2=new Thread()  
           {  
             public void run() {  
               prepareVideo();  
             }  
           };  
           t1.start();  
           t2.start();  
           System.out.println("Started recording at "+new Date());  
      }  


Explanation:
1) Two threads are started in this module when user starts the recording
2) First thread calls the takeScreenshot module which keeps on taking screenshot of user screen and saves them on local disk.
3) Second thread calls the prepareVideo which monitors the screenshot created in step 2 and add them continuously on the video.

takeScreenshot method:
      public static void takeScreenshot(Robot r)  
      {  
           Dimension size = Toolkit.getDefaultToolkit().getScreenSize();  
           Rectangle rec=new Rectangle(size);  
           if(isRegionSelected)  
           {  
                rec=new Rectangle(c1, c2, c3-c1, c4-c2);  
           }  
           while(!videoComplete)  
           {  
           counter++;  
           BufferedImage img = r.createScreenCapture(rec);  
           try {  
                ImageIO.write(img, inputImgExt, new File(inputImageDir+counter+"."+inputImgExt));  
           } catch (IOException e) {  
                JOptionPane.showMessageDialog(frame, "Got an issue while writing the screenshot to disk "+e.getMessage());  
                System.out.println("Got an issue while writing the screenshot to disk "+e.getMessage());  
                counter--;  
           }  
           }  
      }  

Explanation:
1) If user has selected a region for recording then we set the rectangle with the coordinate value of c1,c2,c3,c4. Otherwise we set the rectangle to be full screen
2) Now we run a loop until videoComplete is false (remains false until user press stop recording.
3) Now we capture the region and write the same to the input image directory.
4) So when user starts the recording this method keeps on taking screenshot and saves them into disk.

prepareVideo method:
      public static void prepareVideo()  
      {  
           File scanFolder=new File(inputImageDir);  
           while(!videoComplete)  
           {  
                File[] inputFiles=scanFolder.listFiles();  
                try {  
                     getRobot().delay(500);  
                } catch (Exception e) {  
                }  
                //for(int i=0;i<scanFolder.list().length;i++)  
                for(int i=0;i<inputFiles.length;i++)  
                {  
                     //imgProcessed++;  
                     addImageToVideo(inputFiles[i].getAbsolutePath());  
                     //String imgToAdd=scanFolder.getAbsolutePath()+File.separator+imgProcessed+"."+inputImgExt;  
                     //addImageToVideo(imgToAdd);  
                     //new File(imgToAdd).delete();  
                     inputFiles[i].delete();  
                }  
           }  
           File[] inputFiles=scanFolder.listFiles();  
           for(int i=0;i<inputFiles.length;i++)  
           {  
                addImageToVideo(inputFiles[i].getAbsolutePath());  
                inputFiles[i].delete();  
           }  
      }  

Explanation:
1) We start a loop which will run until video complete is set true (done only when user press stop recording)
2) We keep on monitoring the input  Image directory
3) We traverse each file found in the input image directory and add those images to video using the addImageToVideo method. After the image has been added we delete the image
4) Using the loop in step1 we keep on repeating step 2 and 3 so that each image gets added to video. We added a delay of 500ms so that this module does not picks a half created image from the takeScreenshot module
5) When user press stop recording the loop gets broken. Now we finally traverse the input image directory and add the remaining images to video.

addImageToVideo method:
      public static void addImageToVideo(String imgPath)  
      {  
           try {  
                getRecorder().record(getFrameConverter().convert(cvLoadImage(imgPath)));  
           } catch (Exception e) {  
                JOptionPane.showMessageDialog(frame, "Exception while adding image to video "+e.getMessage());  
                System.out.println("Exception while adding image to video "+e.getMessage());  
           }  
      }  

Explanation:
1) cvLoadImage is used to load the image passed as argument
2) We call the convert method to convert the image to frame which could be used by the recorder
3) We pass the frame obtained in step 2 and add the same in the recorder by calling the record method.

getFrameConverter method:
      public static OpenCVFrameConverter.ToIplImage getFrameConverter()  
      {  
           OpenCVFrameConverter.ToIplImage grabberConverter = new OpenCVFrameConverter.ToIplImage();  
           return grabberConverter;  
      }  

Explanation:
1) We make an object of OpenCVFrameConverter.ToIplImage named grabberConverter and returns this object for other modules.

stopRecording method:
      public static void stopRecording()  
      {  
           try {  
                videoComplete=true;  
                System.out.println("Stopping recording at "+new Date());  
                t1.join();  
                System.out.println("Screenshot thread complete");  
                t2.join();  
                System.out.println("Video maker thread complete");  
                getRecorder().stop();  
                System.out.println("Recording has been saved successfully at "+new File(outputVideo).getAbsolutePath());  
                JOptionPane.showMessageDialog(frame, "Recording has been saved successfully at "+new File(outputVideo).getAbsolutePath());  
           } catch (Exception e) {  
                System.out.println("Exception while stopping the recorder "+e.getMessage());  
           }  
      }  


Explanation:
1) After user press the stop recording, we wait for both the threads to complete.
2) After thread completes, we stop the recorder and show the video path to user.

Output:

 Started recording at Sun Dec 18 18:29:36 IST 2016  
 Stopping recording at Sun Dec 18 18:29:51 IST 2016  
 Screenshot thread complete  
 Video maker thread complete  
 Recording has been saved successfully at C:\Users\anjain\workspace\BrowserMobProxy\cooltrickshome\recording.mp4  
 Exiting...libpng error: PNG unsigned integer out of range  
 Output #0, mp4, to 'recording.mp4':  
   Stream #0:0: Video: mpeg4, yuv420p, 1920x1080, q=2-31, 9 kb/s, 3 tbn, 3 tbc  

Full Program:

ScreenRecorder.java
 package com.cooltrickshome;  
 import static org.bytedeco.javacpp.opencv_imgcodecs.cvLoadImage;  
 import java.awt.AWTException;  
 import java.awt.Dimension;  
 import java.awt.FlowLayout;  
 import java.awt.Rectangle;  
 import java.awt.Robot;  
 import java.awt.Toolkit;  
 import java.awt.event.ActionEvent;  
 import java.awt.event.ActionListener;  
 import java.awt.image.BufferedImage;  
 import java.io.File;  
 import java.io.IOException;  
 import java.util.Date;  
 import javax.imageio.ImageIO;  
 import javax.swing.JButton;  
 import javax.swing.JFrame;  
 import javax.swing.JLabel;  
 import javax.swing.JOptionPane;  
 import org.bytedeco.javacpp.avcodec;  
 import org.bytedeco.javacv.FFmpegFrameRecorder;  
 import org.bytedeco.javacv.OpenCVFrameConverter;  
 public class ScreenRecorder{  
      public static boolean videoComplete=false;  
      public static String inputImageDir="inputImgFolder"+File.separator;  
      public static String inputImgExt="png";  
      public static String outputVideo="recording.mp4";   
      public static int counter=0;  
      public static int imgProcessed=0;  
      public static FFmpegFrameRecorder recorder=null;  
      public static int videoWidth=1920;  
      public static int videoHeight=1080;  
      public static int videoFrameRate=3;  
      public static int videoQuality=0; // 0 is the max quality  
      public static int videoBitRate=9000;  
      public static String videoFormat="mp4";  
      public static int videoCodec=avcodec.AV_CODEC_ID_MPEG4;  
      public static Thread t1=null;  
      public static Thread t2=null;  
      public static JFrame frame=null;  
      public static boolean isRegionSelected=false;  
      public static int c1=0;  
      public static int c2=0;  
      public static int c3=0;  
      public static int c4=0;  
      public static void main(String[] args) {  
           try {  
                if(getRecorder()==null)  
                {  
                     System.out.println("Cannot make recorder object, Exiting program");  
                     System.exit(0);  
                }  
                if(getRobot()==null)  
                {  
                     System.out.println("Cannot make robot object, Exiting program");  
                     System.exit(0);  
                }  
                File scanFolder=new File(inputImageDir);  
                scanFolder.delete();  
                scanFolder.mkdirs();  
                createGUI();  
           } catch (Exception e) {  
                System.out.println("Exception in program "+e.getMessage());  
           }  
      }  
      public static void createGUI()  
      {  
           frame=new JFrame("Screen Recorder");  
           JButton b1=new JButton("Select Region for Recording");  
           JButton b2=new JButton("Start Recording");  
           JButton b3=new JButton("Stop Recording");  
           JLabel l1=new JLabel("<html><br/>If you dont select a region then full screen recording <br/> will be made when you click on Start Recording</html>");  
           l1.setFont (l1.getFont ().deriveFont (20.0f));  
           b1.addActionListener(new ActionListener() {  
       @Override  
       public void actionPerformed(ActionEvent e) {  
            try {  
                 JOptionPane.showMessageDialog(frame, "A new window will open. Use your mouse to select the region you like to record");  
                          new CropRegion().getImage();  
                     } catch (Exception e1) {  
                          // TODO Auto-generated catch block  
                          System.out.println("Issue while trying to call the module to crop region");  
                          e1.printStackTrace();  
                     }   
       }  
     });  
           b2.addActionListener(new ActionListener() {  
       @Override  
       public void actionPerformed(ActionEvent e) {  
            counter=0;  
         startRecording();  
       }  
     });  
           b3.addActionListener(new ActionListener() {  
       @Override  
       public void actionPerformed(ActionEvent e) {  
         stopRecording();  
         System.out.print("Exiting...");  
         System.exit(0);  
       }  
     });  
           frame.add(b1);  
           frame.add(b2);  
           frame.add(b3);  
           frame.add(l1);  
           frame.setLayout(new FlowLayout(0));  
           frame.setVisible(true);  
           frame.setSize(1000, 170);  
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
      }  
      public static void startRecording()  
      {  
           t1=new Thread()  
           {  
             public void run() {  
               try {  
                          takeScreenshot(getRobot());  
                     } catch (Exception e) {  
                          JOptionPane.showMessageDialog(frame, "Cannot make robot object, Exiting program "+e.getMessage());  
                          System.out.println("Cannot make robot object, Exiting program "+e.getMessage());  
                          System.exit(0);  
                     }  
             }  
           };  
           t2=new Thread()  
           {  
             public void run() {  
               prepareVideo();  
             }  
           };  
           t1.start();  
           t2.start();  
           System.out.println("Started recording at "+new Date());  
      }  
      public static Robot getRobot() throws Exception  
      {  
           Robot r=null;  
           try {  
                r = new Robot();  
                return r;  
           } catch (AWTException e) {  
                JOptionPane.showMessageDialog(frame, "Issue while initiating Robot object "+e.getMessage());  
                System.out.println("Issue while initiating Robot object "+e.getMessage());  
                throw new Exception("Issue while initiating Robot object");  
           }  
      }  
      public static void takeScreenshot(Robot r)  
      {  
           Dimension size = Toolkit.getDefaultToolkit().getScreenSize();  
           Rectangle rec=new Rectangle(size);  
           if(isRegionSelected)  
           {  
                rec=new Rectangle(c1, c2, c3-c1, c4-c2);  
           }  
           while(!videoComplete)  
           {  
           counter++;  
           BufferedImage img = r.createScreenCapture(rec);  
           try {  
                ImageIO.write(img, inputImgExt, new File(inputImageDir+counter+"."+inputImgExt));  
           } catch (IOException e) {  
                JOptionPane.showMessageDialog(frame, "Got an issue while writing the screenshot to disk "+e.getMessage());  
                System.out.println("Got an issue while writing the screenshot to disk "+e.getMessage());  
                counter--;  
           }  
           }  
      }  
      public static void prepareVideo()  
      {  
           File scanFolder=new File(inputImageDir);  
           while(!videoComplete)  
           {  
                File[] inputFiles=scanFolder.listFiles();  
                try {  
                     getRobot().delay(500);  
                } catch (Exception e) {  
                }  
                //for(int i=0;i<scanFolder.list().length;i++)  
                for(int i=0;i<inputFiles.length;i++)  
                {  
                     //imgProcessed++;  
                     addImageToVideo(inputFiles[i].getAbsolutePath());  
                     //String imgToAdd=scanFolder.getAbsolutePath()+File.separator+imgProcessed+"."+inputImgExt;  
                     //addImageToVideo(imgToAdd);  
                     //new File(imgToAdd).delete();  
                     inputFiles[i].delete();  
                }  
           }  
           File[] inputFiles=scanFolder.listFiles();  
           for(int i=0;i<inputFiles.length;i++)  
           {  
                addImageToVideo(inputFiles[i].getAbsolutePath());  
                inputFiles[i].delete();  
           }  
      }  
      public static FFmpegFrameRecorder getRecorder() throws Exception  
      {  
            if(recorder!=null)  
            {  
                 return recorder;  
            }  
            recorder = new FFmpegFrameRecorder(outputVideo,videoWidth,videoHeight);  
            try  
            {  
            recorder.setFrameRate(videoFrameRate);  
      recorder.setVideoCodec(videoCodec);  
      recorder.setVideoBitrate(videoBitRate);  
      recorder.setFormat(videoFormat);  
      recorder.setVideoQuality(videoQuality); // maximum quality  
      recorder.start();  
            }  
            catch(Exception e)  
            {  
                 JOptionPane.showMessageDialog(frame, "Exception while starting the recorder object "+e.getMessage());  
                 System.out.println("Exception while starting the recorder object "+e.getMessage());  
                 throw new Exception("Unable to start recorder");  
            }  
      return recorder;  
      }  
      public static OpenCVFrameConverter.ToIplImage getFrameConverter()  
      {  
           OpenCVFrameConverter.ToIplImage grabberConverter = new OpenCVFrameConverter.ToIplImage();  
           return grabberConverter;  
      }  
      public static void addImageToVideo(String imgPath)  
      {  
           try {  
                getRecorder().record(getFrameConverter().convert(cvLoadImage(imgPath)));  
           } catch (Exception e) {  
                JOptionPane.showMessageDialog(frame, "Exception while adding image to video "+e.getMessage());  
                System.out.println("Exception while adding image to video "+e.getMessage());  
           }  
      }  
      public static void stopRecording()  
      {  
           try {  
                videoComplete=true;  
                System.out.println("Stopping recording at "+new Date());  
                t1.join();  
                System.out.println("Screenshot thread complete");  
                t2.join();  
                System.out.println("Video maker thread complete");  
                getRecorder().stop();  
                System.out.println("Recording has been saved successfully at "+new File(outputVideo).getAbsolutePath());  
                JOptionPane.showMessageDialog(frame, "Recording has been saved successfully at "+new File(outputVideo).getAbsolutePath());  
           } catch (Exception e) {  
                System.out.println("Exception while stopping the recorder "+e.getMessage());  
           }  
      }  
 }  

CropRegion.java
 package com.cooltrickshome;  
 import java.awt.AWTException;  
 import java.awt.Dimension;  
 import java.awt.FlowLayout;  
 import java.awt.Graphics;  
 import java.awt.Rectangle;  
 import java.awt.Robot;  
 import java.awt.Toolkit;  
 import java.awt.event.MouseEvent;  
 import java.awt.event.MouseListener;  
 import java.awt.event.MouseMotionListener;  
 import java.awt.image.BufferedImage;  
 import java.io.IOException;  
 import javax.swing.JFrame;  
 import javax.swing.JLabel;  
 import javax.swing.JOptionPane;  
 public class CropRegion implements MouseListener,  
           MouseMotionListener {  
      int drag_status = 0;  
      int c1;  
      int c2;  
      int c3;  
      int c4;  
      JFrame frame=null;  
      static int counter=0;  
      JLabel background=null;  
      public void getImage() throws AWTException, IOException, InterruptedException {  
           Dimension size = Toolkit.getDefaultToolkit().getScreenSize();  
        Robot robot = new Robot();  
        BufferedImage img = robot.createScreenCapture(new Rectangle(size));  
        ImagePanel panel = new ImagePanel(img);  
        frame=new JFrame();  
        frame.add(panel);  
        frame.setLocation(0, 0);  
        frame.setSize(size);  
        frame.setLayout(new FlowLayout());  
        frame.setUndecorated(true);  
        frame.setVisible(true);  
        frame.addMouseListener(this);  
        frame.addMouseMotionListener(this);  
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);  
      }  
      public void draggedScreen() throws Exception {  
           ScreenRecorder.c1=c1;  
           ScreenRecorder.c2=c2;  
           ScreenRecorder.c3=c3;  
           ScreenRecorder.c4=c4;  
           ScreenRecorder.isRegionSelected=true;  
           JOptionPane.showMessageDialog(frame, "Region Selected.Please click on Start Recording button to record the selected region.");  
           frame.dispose();  
      }  
      public void mouseClicked(MouseEvent arg0) {  
      }  
      public void mouseEntered(MouseEvent arg0) {  
      }  
      public void mouseExited(MouseEvent arg0) {  
      }  
      public void mousePressed(MouseEvent arg0) {  
           paint();  
           this.c1 = arg0.getX();  
           this.c2 = arg0.getY();  
      }  
      public void mouseReleased(MouseEvent arg0) {  
           paint();  
           if (this.drag_status == 1) {  
                this.c3 = arg0.getX();  
                this.c4 = arg0.getY();  
                try {  
                     draggedScreen();  
                } catch (Exception e) {  
                     e.printStackTrace();  
                }  
           }  
      }  
      public void mouseDragged(MouseEvent arg0) {  
           paint();  
           this.drag_status = 1;  
           this.c3 = arg0.getX();  
           this.c4 = arg0.getY();  
      }  
      public void mouseMoved(MouseEvent arg0) {  
      }  
      public void paint() {  
           Graphics g = frame.getGraphics();  
           frame.repaint();  
           int w = this.c1 - this.c3;  
           int h = this.c2 - this.c4;  
           w *= -1;  
           h *= -1;  
           if (w < 0) {  
                w *= -1;  
           }  
           g.drawRect(this.c1, this.c2, w, h);  
      }  
 }  

ImagePanel.java
 package com.cooltrickshome;  
 import java.awt.Dimension;  
 import java.awt.Graphics;  
 import java.awt.Image;  
 import javax.swing.ImageIcon;  
 import javax.swing.JPanel;  
 class ImagePanel  
  extends JPanel  
 {  
  private Image img;  
  public ImagePanel(String img)  
  {  
   this(new ImageIcon(img).getImage());  
  }  
  public ImagePanel(Image img)  
  {  
   this.img = img;  
   Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));  
   setPreferredSize(size);  
   setMinimumSize(size);  
   setMaximumSize(size);  
   setSize(size);  
   setLayout(null);  
  }  
  public void paintComponent(Graphics g)  
  {  
   g.drawImage(this.img, 0, 0, null);  
  }  
 }  


Note:
I am not sure if there could be a way to reduce the resulting video size. If you have please let me know
Right now I am using an int variable named counter to name the screenshot. For a long recording this will cause an issue since int range will be exhausted. Need to think about an alternative for same.
I have recorded for few minutes but haven't tested for longer duration.

If you have any suggestions on this, please feel free to contact me via comments or directly at my email cs.anurag.jain@gmail.com :)

Hope it helps :)