Mad*_*sen 14 java open-source thumbnails
我正在寻找一个开源Java库来为给定的URL生成缩略图.我需要捆绑此功能,而不是呼叫外部服务,例如Amazon或websnapr.
http://www.webrenderer.com/在这篇文章中提到:服务器生成的网页截图,但它是一个商业解决方案.
我希望有一个基于Java的解决方案,但可能需要考虑执行一个外部进程,如khtml2png,或集成html2ps之类的东西.
有什么建议?
首先想到的是使用AWT捕获屏幕抓取(参见下面的代码).您可以查看捕获JEditorPane,JDIC WebBrowser控件或SWT 浏览器(通过AWT嵌入支持).后两者嵌入了原生浏览器(IE,Firefox),因此引入了依赖关系; JEditorPane HTML支持在HTML 3.2处停止.可能这些都不适用于无头系统.
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JLabel;
public class Capture {
private static final int WIDTH = 128;
private static final int HEIGHT = 128;
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
public void capture(Component component) {
component.setSize(image.getWidth(), image.getHeight());
Graphics2D g = image.createGraphics();
try {
component.paint(g);
} finally {
g.dispose();
}
}
private BufferedImage getScaledImage(int width, int height) {
BufferedImage buffer = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffer.createGraphics();
try {
g.drawImage(image, 0, 0, width, height, null);
} finally {
g.dispose();
}
return buffer;
}
public void save(File png, int width, int height) throws IOException {
ImageIO.write(getScaledImage(width, height), "png", png);
}
public static void main(String[] args) throws IOException {
JLabel label = new JLabel();
label.setText("Hello, World!");
label.setOpaque(true);
Capture cap = new Capture();
cap.capture(label);
cap.save(new File("foo.png"), 64, 64);
}
}
Run Code Online (Sandbox Code Playgroud)