HTMLを画像に簡単に変換してから、作成せずにバイト配列に変換するにはどうすればよいですか
ありがとう
複雑な 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"));
図書館は使えると思います
html2image-0.9.jar
このライブラリは、次のページからダウンロードできます: http://code.google.com/p/java-html2image/
上記のコードByteArrayStream
で a の代わりにin memory を使用するのはどうですか? FileOutputStream
それは少なくともバイト配列になります...
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();
}