Java の中国語フォントが Linux で表示されない (画像内の中国語の文字化けの問題を解決するため)

Java では、以下を使用してサポートされているフォントを決定できます。

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

jdk15 以降は、~/jre/lib/fonts/ にフォールバック ディレクトリを作成し、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);
	}

}

おすすめ

転載: blog.csdn.net/SJshenjian/article/details/54799950#comments_26726898