java - Render image dynamically -
i'm trying render image dynamic html layout. how can set width , height of image dynamically based on height , width of table inside html. mean how can find table width(x)
, height(y)
html
?
jlabel label = new jlabel(html); label.setsize(x, y); bufferedimage image = new bufferedimage(label.getwidth(),label.getheight(),bufferedimage.type_int_argb); graphics2d g2d = (graphics2d)image.getgraphics(); g2d.setcolor(color.white); g2d.setrenderinghint(renderinghints.key_text_antialiasing, renderinghints.value_text_antialias_on); label.paint(g2d); g2d.dispose(); bytearrayoutputstream baos = new bytearrayoutputstream(); try { imageio.write(image, "png", baos); } catch (ioexception e) { e.printstacktrace(); }
below outline of html.
<html> <head>....</head> <body topmargin="0" leftmargin="0"><table border=0 cellpadding=0 cellspacing=0 width=700 style='border-collapse:collapse;table-layout:fixed;width:684pt'> ...... ...... </body></html>
the following code works. idea that, if don't put rendering jlabel
inside container layoutmanager
, need set size of jlabel
yourself. appropriate size can found getpreferredsize()
. should done exclusively in situation. in other cases, should not call setsize()
, should leave layoutmanager
.
the result image:
import java.awt.color; import java.awt.desktop; import java.awt.graphics2d; import java.awt.renderinghints; import java.awt.image.bufferedimage; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import javax.imageio.imageio; import javax.swing.jlabel; import javax.swing.swingutilities; class testpaint { protected void initui() { stringbuilder sb = new stringbuilder("<html>"); sb.append("<table>"); (int = 0; < 5; i++) { sb.append("<tr>"); (int j = 0; j < 5; j++) { sb.append("<td>"); sb.append("cell ").append(i + 1).append(' ').append(j + 1); sb.append("</td>"); } sb.append("</tr>"); } sb.append("</table>"); jlabel label = new jlabel(sb.tostring()); label.setsize(label.getpreferredsize()); bufferedimage image = new bufferedimage(label.getwidth(), label.getheight(), bufferedimage.type_int_argb); graphics2d g2d = (graphics2d) image.getgraphics(); g2d.setcolor(color.white); g2d.setrenderinghint(renderinghints.key_text_antialiasing, renderinghints.value_text_antialias_on); label.paint(g2d); g2d.dispose(); file file = new file("/tmp/test.png"); if (!file.getparentfile().exists()) { file.getparentfile().mkdirs(); } fileoutputstream baos = null; try { baos = new fileoutputstream(file); imageio.write(image, "png", baos); desktop.getdesktop().open(file); } catch (ioexception e) { e.printstacktrace(); } { if (baos != null) { try { baos.close(); } catch (ioexception e) { e.printstacktrace(); } } } } public static void main(string[] args) { swingutilities.invokelater(new runnable() { @override public void run() { new testpaint().initui(); } }); } }
Comments
Post a Comment