Showing posts with label convert. Show all posts
Showing posts with label convert. Show all posts

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, May 27, 2017

Convert JSON to XML using Java

This post will discuss on how you can convert json to xml using Java.

Language Used:
Java

Pom Dependency:
 <!-- https://mvnrepository.com/artifact/org.json/json -->  
 <dependency>  
   <groupId>org.json</groupId>  
   <artifactId>json</artifactId>  
   <version>20170516</version>  
 </dependency>  

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

Program:

main method:
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           String jsonString="{\"name\":\"Virat\",\"sport\":\"cricket\",\"age\":25,\"id\":121,\"lastScores\":[72,23,57,54,36,74,17]}";  
           System.out.println(new Json2XML().json2XML(jsonString));  
      }  

How it works:
1) We call the method json2XML which we created passing the json to be converted
2) The return value of function contains the resulting xml

json2XML method:
      public String json2XML(String jsonString){  
           JSONObject json = new JSONObject(jsonString);  
           String xml = XML.toString(json);  
           return xml;  
      }  

How it works:
1) We pass the Json String to be converted into the JSONObject
2) We use the toString method of XML class passing the json object created in Step1
3) Step2 gives the resulting xml which is then returned.
4) If you want to give a root node for resulting xml then you can provide the root xml node as second argument in toString method from Step2

Full Program:
 package com.cooltrickshome;  
 import org.json.JSONObject;  
 import org.json.XML;  
 public class Json2XML {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           String jsonString="{\"name\":\"Virat\",\"sport\":\"cricket\",\"age\":25,\"id\":121,\"lastScores\":[72,23,57,54,36,74,17]}";  
           System.out.println(new Json2XML().json2XML(jsonString));  
      }  
      public String json2XML(String jsonString){  
           JSONObject json = new JSONObject(jsonString);  
           String xml = XML.toString(json);  
           return xml;  
      }  
 }  

Input:
{"name":"Virat","sport":"cricket","age":25,"id":121,"lastScores":[77,72,23,57,54,36,74,17]}

Output:

<name>Virat</name><lastScores>77</lastScores><lastScores>72</lastScores><lastScores>23</lastScores><lastScores>57</lastScores><lastScores>54</lastScores><lastScores>36</lastScores><lastScores>74</lastScores><lastScores>17</lastScores><id>121</id><sport>cricket</sport><age>25</age>

Hope it helps :)

Friday, May 26, 2017

Convert Json to POJO using Java

If you have a json which you want to map into POJO without writing the full POJO class then you can make use of jsonschema2pojo library. This is an excellent library which would create Java classes using your input JSON

Program Language
Java

Pom Dependency
     <dependency>  
       <groupId>org.jsonschema2pojo</groupId>  
       <artifactId>jsonschema2pojo-core</artifactId>  
       <version>0.4.35</version>  
     </dependency>  

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

Program

main method:
      public static void main(String[] args) {  
           String packageName="com.cooltrickshome";  
           File inputJson= new File("."+File.separator+"input.json");  
           File outputPojoDirectory=new File("."+File.separator+"convertedPojo");  
           outputPojoDirectory.mkdirs();  
           try {  
                new JsonToPojo().convert2JSON(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", ""));  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                System.out.println("Encountered issue while converting to pojo: "+e.getMessage());  
                e.printStackTrace();  
           }  
      }  


How it works:
1)  packageName defines the package name of the output pojo class
2) inputJson defines the json which need to be converted to POJO
3) outputPojoDirectory is the local path where pojo files would be created
4) We call the convert2JSON method which we created passing the input json, output path, packageName and the output pojo class name

convert2JSON method:
      public void convert2JSON(URL inputJson, File outputPojoDirectory, String packageName, String className) throws IOException{  
           JCodeModel codeModel = new JCodeModel();  
           URL source = inputJson;  
           GenerationConfig config = new DefaultGenerationConfig() {  
           @Override  
           public boolean isGenerateBuilders() { // set config option by overriding method  
           return true;  
           }  
           public SourceType getSourceType(){  
       return SourceType.JSON;  
     }  
           };  
           SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());  
           mapper.generate(codeModel, className, packageName, source);  
           codeModel.build(outputPojoDirectory);  
      }  

How it works:
1)  We make object of JCodeModel which will be used to generate Java class
2) We define the configuration for jsonschema2pojo which lets the program know get input source file is JSON (getSourceType method)
3)  Now we pass the config to Schemamapper along with the codeModel created in Step1 which creates the JavaType from provided Json
4) Finally we call the build method to create the output class

Full Program:
 package com.cooltrickshome;  
 import java.io.File;  
 import java.io.IOException;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 import org.jsonschema2pojo.DefaultGenerationConfig;  
 import org.jsonschema2pojo.GenerationConfig;  
 import org.jsonschema2pojo.Jackson2Annotator;  
 import org.jsonschema2pojo.SchemaGenerator;  
 import org.jsonschema2pojo.SchemaMapper;  
 import org.jsonschema2pojo.SchemaStore;  
 import org.jsonschema2pojo.SourceType;  
 import org.jsonschema2pojo.rules.RuleFactory;  
 import com.sun.codemodel.JCodeModel;  
 public class JsonToPojo {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String packageName="com.cooltrickshome";  
           File inputJson= new File("."+File.separator+"input.json");  
           File outputPojoDirectory=new File("."+File.separator+"convertedPojo");  
           outputPojoDirectory.mkdirs();  
           try {  
                new JsonToPojo().convert2JSON(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", ""));  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                System.out.println("Encountered issue while converting to pojo: "+e.getMessage());  
                e.printStackTrace();  
           }  
      }  
      public void convert2JSON(URL inputJson, File outputPojoDirectory, String packageName, String className) throws IOException{  
           JCodeModel codeModel = new JCodeModel();  
           URL source = inputJson;  
           GenerationConfig config = new DefaultGenerationConfig() {  
           @Override  
           public boolean isGenerateBuilders() { // set config option by overriding method  
           return true;  
           }  
           public SourceType getSourceType(){  
       return SourceType.JSON;  
     }  
           };  
           SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());  
           mapper.generate(codeModel, className, packageName, source);  
           codeModel.build(outputPojoDirectory);  
      }  
 }  

Input Json:
 {"name":"Virat","sport":"cricket","age":25,"id":121,"lastScores":[77,72,23,57,54,36,74,17]}  

Output Class generated:
 package com.cooltrickshome;  
 import java.util.ArrayList;  
 import java.util.HashMap;  
 import java.util.List;  
 import java.util.Map;  
 import com.fasterxml.jackson.annotation.JsonAnyGetter;  
 import com.fasterxml.jackson.annotation.JsonAnySetter;  
 import com.fasterxml.jackson.annotation.JsonIgnore;  
 import com.fasterxml.jackson.annotation.JsonInclude;  
 import com.fasterxml.jackson.annotation.JsonProperty;  
 import com.fasterxml.jackson.annotation.JsonPropertyOrder;  
 import org.apache.commons.lang.builder.EqualsBuilder;  
 import org.apache.commons.lang.builder.HashCodeBuilder;  
 import org.apache.commons.lang.builder.ToStringBuilder;  
 @JsonInclude(JsonInclude.Include.NON_NULL)  
 @JsonPropertyOrder({  
   "name",  
   "sport",  
   "age",  
   "id",  
   "lastScores"  
 })  
 public class Input {  
   @JsonProperty("name")  
   private String name;  
   @JsonProperty("sport")  
   private String sport;  
   @JsonProperty("age")  
   private Integer age;  
   @JsonProperty("id")  
   private Integer id;  
   @JsonProperty("lastScores")  
   private List<Integer> lastScores = new ArrayList<Integer>();  
   @JsonIgnore  
   private Map<String, Object> additionalProperties = new HashMap<String, Object>();  
   @JsonProperty("name")  
   public String getName() {  
     return name;  
   }  
   @JsonProperty("name")  
   public void setName(String name) {  
     this.name = name;  
   }  
   public Input withName(String name) {  
     this.name = name;  
     return this;  
   }  
   @JsonProperty("sport")  
   public String getSport() {  
     return sport;  
   }  
   @JsonProperty("sport")  
   public void setSport(String sport) {  
     this.sport = sport;  
   }  
   public Input withSport(String sport) {  
     this.sport = sport;  
     return this;  
   }  
   @JsonProperty("age")  
   public Integer getAge() {  
     return age;  
   }  
   @JsonProperty("age")  
   public void setAge(Integer age) {  
     this.age = age;  
   }  
   public Input withAge(Integer age) {  
     this.age = age;  
     return this;  
   }  
   @JsonProperty("id")  
   public Integer getId() {  
     return id;  
   }  
   @JsonProperty("id")  
   public void setId(Integer id) {  
     this.id = id;  
   }  
   public Input withId(Integer id) {  
     this.id = id;  
     return this;  
   }  
   @JsonProperty("lastScores")  
   public List<Integer> getLastScores() {  
     return lastScores;  
   }  
   @JsonProperty("lastScores")  
   public void setLastScores(List<Integer> lastScores) {  
     this.lastScores = lastScores;  
   }  
   public Input withLastScores(List<Integer> lastScores) {  
     this.lastScores = lastScores;  
     return this;  
   }  
   @Override  
   public String toString() {  
     return ToStringBuilder.reflectionToString(this);  
   }  
   @JsonAnyGetter  
   public Map<String, Object> getAdditionalProperties() {  
     return this.additionalProperties;  
   }  
   @JsonAnySetter  
   public void setAdditionalProperty(String name, Object value) {  
     this.additionalProperties.put(name, value);  
   }  
   public Input withAdditionalProperty(String name, Object value) {  
     this.additionalProperties.put(name, value);  
     return this;  
   }  
   @Override  
   public int hashCode() {  
     return new HashCodeBuilder().append(name).append(sport).append(age).append(id).append(lastScores).append(additionalProperties).toHashCode();  
   }  
   @Override  
   public boolean equals(Object other) {  
     if (other == this) {  
       return true;  
     }  
     if ((other instanceof Input) == false) {  
       return false;  
     }  
     Input rhs = ((Input) other);  
     return new EqualsBuilder().append(name, rhs.name).append(sport, rhs.sport).append(age, rhs.age).append(id, rhs.id).append(lastScores, rhs.lastScores).append(additionalProperties, rhs.additionalProperties).isEquals();  
   }  
 }  

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 :)

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 :)

Sunday, December 11, 2016

Images to Movie Converter using Java

This blog post will help you to convert your images to a video using Java.

Language Used:
Java

Git Location:
https://github.com/csanuragjain/converter/tree/master/ImageToMovie

Reference:
http://stackoverflow.com/questions/13643046/how-to-convert-images-into-video-in-android-using-javacv
http://stackoverflow.com/questions/28721396/convert-images-to-video-in-android
http://stackoverflow.com/questions/15867696/javacv-opencv-cvloadimage-not-working

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>   

Program:

Main method:
       public static void main(String []args)  
        {  
                 Scanner s=new Scanner(System.in);  
                 System.out.println("Enter the directory path of images (for eg c:\\test)");  
                 String imgPath=s.nextLine();  
                 System.out.println("Enter the directory with video file name where resulting video will be saved (for eg c:\\test\\abc.mp4)");  
                 String vidPath=s.nextLine();  
                 ArrayList<String> links = new ArrayList<>();  
                 File f=new File(imgPath);  
                 File[] f2=f.listFiles();  
                 for(File f3:f2)  
                 {  
                      links.add(f3.getAbsolutePath());  
                 }  
                 convertJPGtoMovie(links, vidPath);  
                 System.out.println("Video has been created at "+vidPath);  
                 s.close();  
        }  

How it works:
1) We make a simple scanner object to get user input
2) We ask the directory containing the images to be converted to video
3) We ask user the resulting directory along with video file name from user.
4) We scan the directory obtained from step 2 and save all the image path in a ArrayList.
5) Now we call convertJPGtoMovie along with the ArrayList (containing all images path) and the resulting video path

convertJPGtoMovie method:
       public static void convertJPGtoMovie(ArrayList<String> links, String vidPath)  
       {  
            OpenCVFrameConverter.ToIplImage grabberConverter = new OpenCVFrameConverter.ToIplImage();  
            FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(vidPath,640,720);  
            try {  
                 recorder.setFrameRate(1);  
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_MPEG4);  
        recorder.setVideoBitrate(9000);  
        recorder.setFormat("mp4");  
        recorder.setVideoQuality(0); // maximum quality  
        recorder.start();  
              for (int i=0;i<links.size();i++)  
              {  
               recorder.record(grabberConverter.convert(cvLoadImage(links.get(i))));  
              }  
              recorder.stop();  
             }  
             catch (org.bytedeco.javacv.FrameRecorder.Exception e){  
               e.printStackTrace();  
             }  
       }  

How it works:
1) We make an object of ToIplImage named grabberConverter which we are going to use later for converting from IplImage to Frame Object
2) We make a FFmpegFrameRecorder object named recorder which would help to convert our images to video. It takes 3 argument. First is the video file path which need to be created. Second argument defines the image width and third argument defines the image height.
3) We define the frame rate of the resulting video. Similarly we need to set other video parameters like video codec, bitrate, format, quality.
4) After video configuration has been made we start the recording by calling the start method.
5) Now cvLodImage method takes the image we passed and convert them into IplImage. Now we use grabberConverter from step1 to convert the IplImage into Frame.
6) We utilise the record method of FFmpegFrameRecorder which takes the Frame from step5 and place it in the resulting video. This way our video has the first image.
7) Step5 and Step6 are repeated over loop covering all the images which need to be embedded into the video.
8) After all images are covered, we call the stop button which marks the completion of our video.

Output:
 Enter the directory path of images (for eg c:\test)  
 C:\Users\anurag\Desktop\images\extra  
 Enter the directory where resulting video will be saved (for eg c:\test\abc.mp4)  
 C:\Users\anjain\Desktop\images\extra\5.mp4  
 Video has been created at C:\Users\anurag\Desktop\images\extra\5.mp4  
 Output #0, mp4, to 'C:\Users\anjain\Desktop\images\extra\5.mp4':  
   Stream #0:0: Video: mpeg4, yuv420p, 640x720, q=2-31, 9 kb/s, 1 tbn, 1 tbc  

Full Program:
 package com.cooltrickshome;  
 import static org.bytedeco.javacpp.opencv_imgcodecs.*;  
 import java.io.File;  
 import java.io.IOException;  
 import java.util.ArrayList;  
 import java.util.Scanner;  
 import org.bytedeco.javacpp.avcodec;  
 import org.bytedeco.javacv.FFmpegFrameRecorder;  
 import org.bytedeco.javacv.OpenCVFrameConverter;  
 public class ImageToMovie {  
      /**  
       * @param args  
       * @throws IOException   
       */  
       public static void main(String []args)  
        {  
                 Scanner s=new Scanner(System.in);  
                 System.out.println("Enter the directory path of images (for eg c:\\test)");  
                 String imgPath=s.nextLine();  
                 System.out.println("Enter the directory with video file name where resulting video will be saved (for eg c:\\test\\abc.mp4)");  
                 String vidPath=s.nextLine();  
                 ArrayList<String> links = new ArrayList<>();  
                 File f=new File(imgPath);  
                 File[] f2=f.listFiles();  
                 for(File f3:f2)  
                 {  
                      links.add(f3.getAbsolutePath());  
                 }  
                 convertJPGtoMovie(links, vidPath);  
                 System.out.println("Video has been created at "+vidPath);  
                 s.close();  
        }  
       public static void convertJPGtoMovie(ArrayList<String> links, String vidPath)  
       {  
            OpenCVFrameConverter.ToIplImage grabberConverter = new OpenCVFrameConverter.ToIplImage();  
            FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(vidPath,640,720);  
            try {  
                 recorder.setFrameRate(1);  
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_MPEG4);  
        recorder.setVideoBitrate(9000);  
        recorder.setFormat("mp4");  
        recorder.setVideoQuality(0); // maximum quality  
        recorder.start();  
              for (int i=0;i<links.size();i++)  
              {  
               recorder.record(grabberConverter.convert(cvLoadImage(links.get(i))));  
              }  
              recorder.stop();  
             }  
             catch (org.bytedeco.javacv.FrameRecorder.Exception e){  
               e.printStackTrace();  
             }  
       }  
 }  

Hope it helps :)

Wednesday, November 23, 2016

Convert Base64 encoded string to Image using Java

This program will help you convert a base64 string to an image and then save the image to the current directory using Java.

Language Used:
Java

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

Pom Dependency:
 <dependency>  
   <groupId>commons-codec</groupId>  
   <artifactId>commons-codec</artifactId>  
   <version>1.10</version>  
 </dependency>  

Program:

Main Method:
      public static void main(String[] args) throws IOException {  
           // TODO Auto-generated method stub  
           Scanner s=new Scanner(System.in);  
           System.out.println("Enter base64 string to be converted to image");  
           String base64=s.nextLine();  
           byte[] base64Val=convertToImg(base64);  
           writeByteToImageFile(base64Val, "image.png");  
           System.out.println("Saved the base64 as image in current directory with name image.png");  
      }  

How it works:
1) First we make a scanner object and ask user to enter the base64 string which need to be converted to image.
2) We call the convertToImg method which convert the base64 string to byte[]
3) We pass the above retrieved byte[] as argument to writeByteToImageFile method. This will convert the byte[] to image and will save as image.png which was the second argument.

convertToImg method:
 public static byte[] convertToImg(String base64) throws IOException  
      {  
           return Base64.decodeBase64(base64);  
      }  

How it works:
1) We pass the base64 string to Base64.decodeBase64 method which converts the base64 string to byte[]

writeByteToImageFile method:
 public static void writeByteToImageFile(byte[] imgBytes, String imgFileName) throws IOException  
      {  
           File imgFile = new File(imgFileName);  
           BufferedImage img = ImageIO.read(new ByteArrayInputStream(imgBytes));  
           ImageIO.write(img, "png", imgFile);  
      }  

How it works:
1) This method obtains the byte[] and the image file name
2) We make a file object pointing to image file name
3) We make a BufferedImage object from the image bytes we passed
4) We use the ImageIO.write to write the BufferedImage into a physical file.

Output:
 Enter base64 string to be converted to image  
 /9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TIwOo6OIFtvmDyW2OvzruanoMHZGz69bVxPKutGp8LwvoVCfwW1cVl3RplwmHZk9eFtjxWPeJqlwh9pE9aFs/yeI1f4rL4oxHSk81Uz1mWfVltj0mGHSJQSudtvqdKVdCQoFlQUmRUFIK2hSQVUpIFKAMqCiKSySNEsDRQSQQpBFKAEYIUEFJQksYmAPFH5qGDSYnCOZysd4WLRJjFyxJK4sS5uxIU2QZeF4o1oLZbb2s7HBrnA2bcOyDrd6cw7TY1caTUReOpOmjizY2pWjKw2Pa92Z1jk1p5DmT4n6AeJXNqtSpvlj0N2HE47vqbJjwdQVyWbioJVglCSCVNEBTQASgVUnKRYypyiwWpyiyKUcosmk5RYpOUWKTlFlhYhAIGVKQVNQkqUklxqyRiyoKSAsSUEYKHKCSgqCAoJCzRDCxYCEgqWCkqAUlAW3KB3Ndi4xroPkFiyTVSDVYkkIQS1AbTg57RHhssog3DVmupBUjJClEEKQVBEGVtUmJKAkIClSCUAUkhDE//9k=  
 Saved the base64 as image in current directory with name image.png  

Full Program:
 package com.cooltrickshome;  
 import java.awt.image.BufferedImage;  
 import java.io.ByteArrayInputStream;  
 import java.io.File;  
 import java.io.IOException;  
 import java.util.Scanner;  
 import javax.imageio.ImageIO;  
 import org.apache.commons.codec.binary.Base64;  
 public class Base64ToImage {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) throws IOException {  
           // TODO Auto-generated method stub  
           Scanner s=new Scanner(System.in);  
           System.out.println("Enter base64 string to be converted to image");  
           String base64=s.nextLine();  
           byte[] base64Val=convertToImg(base64);  
           writeByteToImageFile(base64Val, "image.png");  
           System.out.println("Saved the base64 as image in current directory with name image.png");  
      }  
      public static byte[] convertToImg(String base64) throws IOException  
      {  
           return Base64.decodeBase64(base64);  
      }  
      public static void writeByteToImageFile(byte[] imgBytes, String imgFileName) throws IOException  
      {  
           File imgFile = new File(imgFileName);  
           BufferedImage img = ImageIO.read(new ByteArrayInputStream(imgBytes));  
           ImageIO.write(img, "png", imgFile);  
      }  
 }  

Hope it helps :)