截取的google的效果,将就吧,不是特别好。 但是作为普通的应用,我想这个效果我已经很满意了。

注意,里面的

this.setVisible(true);

这句话如果运行在一些不能显示图形界面的机器上,请屏蔽掉它,不过这样的话,网页里的图片就不能被截取了。







完整的源代码如下:


  1. import java.awt.Graphics2D;
  2. import java.awt.RenderingHints;
  3. import java.awt.geom.AffineTransform;
  4. import java.awt.image.BufferedImage;
  5. import java.awt.image.ColorModel;
  6. import java.awt.image.WritableRaster;
  7. import java.io.*;
  8. import javax.imageio.*;
  9. import javax.swing.*;

  10. /**
  11. * HTML2JPG,HTML页面转图片的实现方法。
  12. *
  13. * @author 老紫竹(Java世纪网,java2000.net)
  14. */
  15. public class Test extends JFrame {

  16. public Test(String url, File file) throws Exception {
  17. JEditorPane editorPane = new JEditorPane();
  18. editorPane.setEditable(false);
  19. editorPane.setPage(url);
  20. JScrollPane jsp = new JScrollPane(editorPane);
  21. getContentPane().add(jsp);
  22. this.setLocation(0, 0);
  23. this.setVisible(true); // 如果这里不设置可见,则里面的图片等无法截取

  24. // 如果不延时,则图片等可能没有时间下载显示
  25. // 具体的秒数需要根据网速等调整
  26. Thread.sleep(5 * 1000);

  27. setSize(10000, 10000);

  28. pack();
  29. // BufferedImage image = new BufferedImage(editorPane.getWidth(),
  30. // editorPane.getHeight(), BufferedImage.TYPE_INT_RGB);
  31. BufferedImage image = new BufferedImage(editorPane.getWidth(), editorPane.getHeight(),
  32. BufferedImage.TYPE_INT_RGB);
  33. Graphics2D graphics2D = image.createGraphics();
  34. editorPane.paint(graphics2D);

  35. BufferedImage image1 = resize(image, 600, 400);

  36. ImageIO.write(image1, "jpg", file);
  37. dispose();
  38. }

  39. public static void main(String[] args) throws Exception {
  40. new Test("http://www.google.cn", new File("d:/file.jpg"));
  41. }

  42. public static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
  43. // targetW,targetH分别表示目标长和宽
  44. int type = source.getType();
  45. BufferedImage target = null;
  46. double sx = (double) targetW / source.getWidth();
  47. double sy = (double) targetH / source.getHeight();
  48. // 这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放
  49. // 则将下面的if else语句注释即可
  50. if (sx > sy) {
  51. sx = sy;
  52. targetW = (int) (sx * source.getWidth());
  53. // } else {
  54. // sy = sx;
  55. // targetH = (int) (sy * source.getHeight());
  56. }
  57. if (type == BufferedImage.TYPE_CUSTOM) { // handmade
  58. ColorModel cm = source.getColorModel();
  59. WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);
  60. boolean alphaPremultiplied = cm.isAlphaPremultiplied();
  61. target = new BufferedImage(cm, raster, alphaPremultiplied, null);
  62. } else
  63. target = new BufferedImage(targetW, targetH, type);
  64. Graphics2D g = target.createGraphics();
  65. // smoother than exlax:
  66. g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
  67. g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
  68. g.dispose();
  69. return target;
  70. }
  71. }