截取的google的效果,將就吧,不是特別好。 但是作為普通的應用,我想這個效果我已經很滿意了。
注意,裡面的
this.setVisible(true);
這句話如果運行在一些不能顯示圖形界面的機器上,請屏蔽掉它,不過這樣的話,網頁裡的圖片就不能被截取了。
效果圖:
完整的源代碼如下:
import Java.awt.Graphics2D;
import Java.awt.RenderingHints;
import Java.awt.geom.AffineTransform;
import Java.awt.image.BufferedImage;
import Java.awt.image.ColorModel;
import Java.awt.image.WritableRaster;
import Java.io.*;
import Javax.imageio.*;
import Javax.swing.*;
/**
* HTML2JPG,Html頁面轉圖片的實現方法。
*
* @author 老紫竹(Java世紀網,Java2000.Net)
*/
public class Test extends JFrame {
public Test(String url, File file) throws Exception {
JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
editorPane.setPage(url);
JScrollPane JSP = new JScrollPane(editorPane);
getContentPane().add(JSP);
this.setLocation(0, 0);
this.setVisible(true); // 如果這裡不設置可見,則裡面的圖片等無法截取
// 如果不延時,則圖片等可能沒有時間下載顯示
// 具體的秒數需要根據網速等調整
Thread.sleep(5 * 1000);
setSize(10000, 10000);
pack();
// BufferedImage image = new BufferedImage(editorPane.getWidth(),
// editorPane.getHeight(), BufferedImage.TYPE_INT_RGB);
BufferedImage image = new BufferedImage(editorPane.getWidth(), editorPane.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = image.createGraphics();
editorPane.paint(graphics2D);
BufferedImage image1 = resize(image, 600, 400);
ImageIO.write(image1, "jpg", file);
dispose();
}
public static void main(String[] args) throws Exception {
new Test("http://www.google.cn", new File("d:/file.jpg"));
}
public static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
// targetW,targetH分別表示目標長和寬
int type = source.getType();
BufferedImage target = null;
double sx = (double) targetW / source.getWidth();
double sy = (double) targetH / source.getHeight();
// 這裡想實現在targetW,targetH范圍內實現等比縮放。如果不需要等比縮放
// 則將下面的if else語句注釋即可
if (sx > sy) {
sx = sy;
targetW = (int) (sx * source.getWidth());
// } else {
// sy = sx;
// targetH = (int) (sy * source.getHeight());
}
if (type == BufferedImage.TYPE_CUSTOM) { // handmade
ColorModel cm = source.getColorModel();
WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);
boolean alphaPremultiplied = cm.isAlphaPremultiplIEd();
target = new BufferedImage(cm, raster, alphaPremultiplIEd, null);
} else
target = new BufferedImage(targetW, targetH, type);
Graphics2D g = target.createGraphics();
// smoother than exlax:
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
g.dispose();
return target;
}
}