Wednesday, February 15, 2012

HTML TO JPEG IN JAVA

Hi,
   Today i will explain you how to convert html page to jpeg in java.

     public class HTML2JPEG{
          public static void main(String args[]){
              //for reading the input file data
              DataInputStream dis = new DataInputStream(new FileInputStream(new File("file.html")));
              //for writing the output file data
              FileOutputStream fos = new FielOutputStream(new File("testfile.jpeg"));
              bytes[]  bytes = new byte[1024];
              StringBuffer sb = new StringBuffer();
              while(dis.available() >0){
                      sb.append(new String(bytes, 0, dis. read(bytes)));
             }
              String str = sb.toString();
              //using awt package for creating the image
              JLabel label = new JLabel(str);
              label.setSize(800,800);
            
               BufferedImage image = new BufferedImage(label.getWidth(),label.getHeight(),BufferedImage.TYPE_BYTE_RGB);
               Graphics g = image.getGraphics();//or else can use createGraphics()              
               g.setColor(Color.BLACK);            
               label.paint(g);
               g.dispose();
            
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              ImageIO.write(image, "jpeg",baos);
              //read the data from baos to byte[]
              byte[] bytesData = baos.toByteArray();  
               //Or Else you can use FileOutputStream
              ImageIO.write(image, "jpeg",fos);
              System.out.println("Completed");
         }
}

Please correct me if at all there is any changes need to be done in the above program.Or else if there is a better way than this, post it immediately.Any help appreciated.