Linux下Java中文字体不显示(解决图像中文乱码问题)

时间:2021-10-23 06:41:27

在Java中可以使用如下判断支持的字体

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironm

ent();
String[] fontFamilies = ge.getAvailableFontFamilyNames();
for (String s : fontFamilies) {
    System.out.println(s);
}

在jdk15以后,只需在~/jre/lib/fonts/下建一个fallback目录,把你想在java中使用的字体烤贝到这个目录中即可

以下方法在fc6下测试通过,假设用户的jre路径为 /usr/java/jdk1.6.0_03/jre/
#cd /usr/java/jdk1.6.0_03/jre/lib/fonts
#sudo mkdir fallback
将C:\WINDOWS\Fonts\simsun.ttc拷贝到 /usr/java/jdk1.6.0_03/jre/lib/fonts/fallback文件夹内 ok!
 
win7中没有,win2003 有simsun.ttc

测试程序

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class Test {

public static void main(String[] args) throws Exception {
int width = 100;
int height = 100;
System.err.println(System.getProperty("sun.jnu.encoding"));
String s1 = "时段";
// String s2 = new String("你好".getBytes(System.getProperty("sun.jnu.encoding")), "UTF-8");
// String s3 = new String("你好".getBytes("GBK"), System.getProperty("sun.jnu.encoding"));
// String s4 = new String("你好".getBytes(), System.getProperty("sun.jnu.encoding"));

File file = new File("/home/image.jpg");

Font font = new Font("Serif", Font.BOLD, 10);
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) bi.getGraphics();
g2.setBackground(Color.WHITE);
g2.clearRect(0, 0, width, height);
g2.setPaint(Color.RED);

FontRenderContext context = g2.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(s1 , context);
double x = (width - bounds.getWidth()) / 2;
double y = (height - bounds.getHeight()) / 2;
double ascent = -bounds.getY();
double baseY = y + ascent;

g2.drawString(s1, (int) x, (int) baseY);

ImageIO.write(bi, "jpg", file);
}

}

测试成功的案例:  http://www.xuefeng66.cn/car