程序是WEB应用,部署在Linux Windows下都没有问题
但是部署到万网的服务器(Unix)下,文字输出成图片,中文就变成了一个个小方块。
我在程序中打印出文字都是汉字,具体代码如下
public void createTextImage(Text text, String destpath) throws IOException {
File img = new File(destpath);
int size = (int) (text.getSize() / text.getRate());
int width = getLength(text.getText()) * (size + 4); // 设置宽度
int height = size + 10; // 设置高度
System.out.print("文字信息:" + text.getSize() + "|缩放:" + text.getRate()
+ "|最终大小:" + size + "|文字内容:" + text.getText() + "|字体:"
+ text.getFamily());
Font font = new Font(text.getFamily(), text.getItalic()
+ text.getBold(), size);
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
// ---------- 增加下面的代码使得背景透明 -----------------
bi = g2.getDeviceConfiguration().createCompatibleImage(width, height,
Transparency.TRANSLUCENT);
g2.dispose();
g2 = bi.createGraphics();
// ---------- 背景透明代码结束 -----------------
g2.setColor(new Color(Integer.parseInt(text.getColor(), 16)));
g2.setFont(font);
/**
* 设置文字在图片中的位置
*
* 这里是居中
*/
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(text.getText(), context);
double x = (width - bounds.getWidth()) / 2;
double y = (height - bounds.getHeight()) / 2;
double ascent = -bounds.getY();
double baseY = y + ascent;
System.out.println("画图之前的文字:" + text.getText());
/**
* 防止生成的文字带有锯齿
*/
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.drawString("你好", (int) x, (int) baseY);//即使这里写死了 生成的图片也还是小方块
// g2.drawString(text.getText(), (width - (getLength(text.getText()) *
// text.getSize())) / 2, height);
g2.dispose();
ImageIO.write(bi, "PNG", img);
}
有Unix经验的朋友帮忙看下哈