java - 用于在服务器端生成网页缩略图的开源 Java 库

标签 java open-source thumbnails

<分区>

我正在寻找一个开源 Java 库来为给定的 URL 生成缩略图。我需要捆绑此功能,而不是调用外部服务,例如 Amazonwebsnapr .

http://www.webrenderer.com/在这篇文章中提到:Server generated web screenshots , 但这是一个商业解决方案。

我希望有一个基于 Java 的解决方案,但可能需要考虑执行外部进程,例如 khtml2png ,或整合类似 html2ps 的东西.

有什么建议吗?

最佳答案

首先想到的是使用 AWT 捕获屏幕抓取(请参见下面的代码)。你可以看看捕获 JEditorPane , JDIC WebBrowser控制或 SWT Browser (通过 AWT embedding support )。后两者嵌入原生浏览器(IE、Firefox),所以引入依赖; JEdi​​torPane HTML 支持在 HTML 3.2 停止。可能这些都不适用于 headless 系统。

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);
    }

}

关于java - 用于在服务器端生成网页缩略图的开源 Java 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/169573/

相关文章:

java - 如何在 android studio 的 Library 模块中使用 getResources() 函数

编译示例 c 文件作为更大的基于 make 的 C 项目的一部分?

delphi - 有没有用 Delphi 制作的开源文字处理器?

api - 如果我提供 API,我的网站是否可以包含 GPL 代码?

c - 如何获取 nautilus 用于给定文件的缩略图?

java - Connection.close() 不会关闭连接,它会使其永远 hibernate ?

java - 当我在 DBPedia 上运行查询时 CATCH block 中的条件

windows-vista - 强制 Windows 显示我的自定义文件类型的缩略图

java - 为什么 long 和 double 在 Java 类的常量池中占用两个条目?

asp.net - 请帮助我使用 image.GetThumbnailImage(它会创建非常低质量的图像)