2010-12-14 52 views
6

我如何可以很容易地將HTML轉換成圖像,然後以字節數組沒有創建將HTML轉換成圖像中的字節數組的Java

感謝

+1

像一個呈現html頁面的「screeenshot」? – 2010-12-14 09:49:36

+0

不,我創建html,我需要通過傳真發送圖片沒有圖像源,所以我想將其轉換爲圖像,然後發送圖像 – cls 2010-12-14 09:58:52

回答

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(); 
} 
+1

我需要將其保存在字節數組中,而不創建它。謝謝 – cls 2010-12-14 10:34:50

12

如果你沒有任何複雜的HTML,你可以使用普通JLabel渲染。下面的代碼會產生這樣的圖像:

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

alt text

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")); 
+0

我不需要創建它只能將它保存爲字節數組 – cls 2010-12-14 10:31:56

+0

您必須經歷類似於'ImageIO.write'的操作。如果不先創建圖像,您不能奇蹟般地構建字節數組。 – aioobe 2010-12-14 10:35:46

+0

@cls字節數組應具有什麼格式? – dacwe 2010-12-14 10:36:16

3

什麼內存ByteArrayStream,而不是在上面的代碼中FileOutputStream使用?這將是一個字節數組,至少...