星期一, 五月 31, 2004

如何在Linux或Unix下,没有启动X Server 使用Java图形库

J2sdk 1.4支持一种所谓的"headless无头"的图形模式.
我们运行在Unix类操作系统下,在X Server没有启动的时候,很多图形库类无法使用,因为这些类需要获得图形设备的一些具体参数,比如dpi,color depth,raster等,在Linux下运行Java application Server经常是不启动X server的,在这种情况下如果需要使用图形类Class.需要在启动的命令行加入以下参数


-Djava.awt.headless=true


JAVA_OPTS=$JAVA_OPTS: -Djava.awt.headless=true

重新启动Application Server如Tomcat,就可以在Servlet中使用这些图形类了.

public BufferedImage DisplayTextPicture(String willtext)
{
int width = 48;
int height = 48;
float size = 8.0f;
int StringH = 8;
BufferedImage buffer = new BufferedImage(width,
height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 =(Graphics2D)buffer.getGraphics();
Font font = new Font("serif", Font.BOLD, StringH);
font = font.deriveFont(size);
FontRenderContext fc = g2.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(willtext,
fc);
width = (int) bounds.getWidth();
height = (int) bounds.getHeight() * 2;
buffer = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
g2 = (Graphics2D)buffer.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(font);
g2.setColor(Color.white);
g2.fillRect(0, 0, width, height);
g2.setColor(Color.red);
String[] tem = willtext.split("\n");
for (int i = 0; i < tem.length; i++)
g2.drawString(tem[i], 0,
(int) - bounds.getY() + i * StringH);
return buffer;
}
public void Display2Servlet(String text,OutputStream os)
{
OutputStream sos=os;

try
{

boolean flag= ImageIO.write(DisplayTextPicture(text), "png", sos);
if(!flag){logger.log(Level.WARNING,"not success");}
sos.flush();
sos.close();
}catch(Exception e)
{
logger.log(Level.WARNING,e.getMessage());
return;
}
}
}

注意:通过 System.setProperty("java.awt.headless", "true");来改变GraphicsEnvirmont()为"无头"模式,可能是不起作用的,所以最好在命令行启动时候加入.