2010-12-14 8 views
6

¿Cómo puedo convertir fácilmente html a la imagen y luego a la matriz de bytes sin crearloconvertir html a la imagen en la matriz de bytes de Java

gracias

+1

¿Le gusta una "captura de pantalla" de una página html renderizada? –

+0

no, creo html y necesito enviarlo por fax con una imagen sin fuente de imagen, así que quiero convertirlo a imagen y luego enviar la imagen – cls

Respuesta

0

Esto no es trivial ya que la visualización de una página HTML puede ser bastante complejo: se tener texto, imágenes, CSS, posiblemente incluso JavaScript para evaluar.

No sé la respuesta, pero tengo algo que podría ayudarlo: codificar iText (una biblioteca de escritura de PDF) para convertir una página HTML en un archivo 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

necesito guardarlo en matriz de bytes, sin para crearlo. Gracias – cls

12

Si usted no tiene ningún tipo de HTML complejo se puede hacer usando una normal de JLabel. El código siguiente producirá esta imagen:

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

    .... 
} 

Si desea simplemente escribir en un archivo:

ImageIO.write(image, "png", new File("test.png")); 
+0

no necesito crearlo solo para guardarlo como array de bytes – cls

+0

Tienes que pasar por algo así como 'ImageIO.write'. No se puede construir mágicamente la matriz de bytes sin tener primero la imagen. – aioobe

+0

@cls ¿Qué formato debe tener la matriz de bytes? – dacwe

3

¿Qué pasa con el uso de una memoria ByteArrayStream en lugar de un FileOutputStream en el código anterior? Eso sería una matriz de bytes, al menos ...

Cuestiones relacionadas