开发者

converting webpage into jpeg image using java

开发者 https://www.devze.com 2022-12-28 14:22 出处:网络
I am building a web application, in Java, where i w开发者_Python百科ant the whole screenshot of the webpage, if i give the URL of the webpage as input.

I am building a web application, in Java, where i w开发者_Python百科ant the whole screenshot of the webpage, if i give the URL of the webpage as input.

The basic idea i have is to capture the display buffer of the rendering component..I have no idea of how to do it.. plz help..


There's a little trick I used for this app:

count down demo app http://img580.imageshack.us/img580/742/capturadepantalla201004wd.png Java application featuring blog.stackoverflow.com page ( click on image to see the demo video )

The problem is you need to have a machine devoted to this.

So, the trick is quite easy.

  • Create an application that takes as argument the URL you want to fetch.

  • Then open it with Desktop.open( url ) that will trigger the current webbrowser.

  • And finally take the screenshot with java.awt.Robot and save it to diks.

Something like:

 class WebScreenShot {
     public static void main( String [] args ) {
         Desktop.getDesktop().open( args[0] );
         Robot robot = new Robot();
         Image image = robot.createScreenCapture( getScreenResolutionSize() );
         saveToDisk( image );
     }
  }

This solution is far from perfect, because it needs the whole OS, but if you can have a VM devoted to this app, you can craw the web and take screenshots of it quite easy.

The problem of having this app as a non-intrusive app is that up to this date, there is not a good html engine renderer for Java.


For a pure-java solution that can scale to support concurrent rendering, you could use a java HTML4/CSS2 browser, such as Cobra, that provides a Swing component for the GUI. When you instantiate this component, you can call it's paint(Graphics g) method to draw itself into an off-screen image

E.g.
Component c = ...; // the browser component
BufferedImage bi = new BufferedImage(c.getWidth(), c.getHeight(), TYPE_INT_RGB)
Graphics2d g = bi.createGraphics();    
c.paint(g);

You can then use the java image API to save this as a JPG.

JPEGImageEncoder encoder = JPEGCodec.createEncoder(new FileOutputStream("screen.jpg"));
enncoder.encode(bi);  // encode the buffered image

Java-based browsers typically pale in comparison with the established native browsers. However, as your goal is static images, and not an interactive browser, a java-based browser may be more than adequate in this regard.

0

精彩评论

暂无评论...
验证码 换一张
取 消