欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

linux下Java字体乱码(解决图像中中文乱码)

程序员文章站 2022-06-13 08:11:09
...

在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);
	}

}
 
 
相关标签: java