7

HTMLを画像に簡単に変換してから、作成せずにバイト配列に変換するにはどうすればよいですか

ありがとう

4

4 に答える 4

13

複雑な html がない場合は、通常の .html を使用してレンダリングできますJLabel。以下のコードは、この画像を生成します。

<html>
  <h1>:)</h1>
  Hello World!<br>
  <img src="http://img0.gmodules.com/ig/images/igoogle_logo_sm.png">
</html>

代替テキスト

public static void main(String... args) throws IOException {

    String html = "<html>" +
            "<h1>:)</h1>" +
            "Hello World!<br>" +
            "<img src=\"http://img0.gmodules.com/ig/images/igoogle_logo_sm.png\">" +
            "</html>";

    JLabel label = new JLabel(html);
    label.setSize(200, 120);

    BufferedImage image = new BufferedImage(
            label.getWidth(), label.getHeight(), 
            BufferedImage.TYPE_INT_ARGB);

    {
        // paint the html to an image
        Graphics g = image.getGraphics();
        g.setColor(Color.BLACK);
        label.paint(g);
        g.dispose();
    }

    // get the byte array of the image (as jpeg)
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "jpg", baos);
    byte[] bytes = baos.toByteArray();

    ....
}

ファイルに書き込むだけの場合:

    ImageIO.write(image, "png", new File("test.png"));
于 2010-12-14T10:10:05.430 に答える
4

図書館は使えると思います

html2image-0.9.jar

このライブラリは、次のページからダウンロードできます: http://code.google.com/p/java-html2image/

于 2011-08-18T00:04:58.097 に答える
3

上記のコードByteArrayStreamで a の代わりにin memory を使用するのはどうですか? FileOutputStreamそれは少なくともバイト配列になります...

于 2012-11-26T22:00:02.890 に答える
0

HTML ページのレンダリングは非常に複雑になる可能性があるため、これは簡単なことではありません。評価するテキスト、画像、CSS、場合によっては JavaScript もあるからです。

答えはわかりませんが、役に立つかもしれないものがあります: iText (PDF 書き込みライブラリ) のコードで、HTML ページを PDF ファイルに変換します。

public static final void convert(final File xhtmlFile, final File pdfFile) throws IOException, DocumentException
{
    final String xhtmlUrl = xhtmlFile.toURI().toURL().toString();
    final OutputStream reportPdfStream = new FileOutputStream(pdfFile);
    final ITextRenderer renderer = new ITextRenderer();
    renderer.setDocument(xhtmlUrl);
    renderer.layout();
    renderer.createPDF(reportPdfStream);
    reportPdfStream.close();
}
于 2010-12-14T09:56:49.090 に答える