由于不想在服务器去安装字体 想通过项目里放置字体文件来防止项目上线字体问题导致画出来的图中文乱码,所以决定使用Font.createFont(int fontFormat, InputStream fontStream)来导入本地字体。
首先我是这样写的
//模板图片
ClassPathResource resource = new ClassPathResource("template/template1.png");
//字体文件
ClassPathResource fontResource = new ClassPathResource("font/simsun.ttf");
// 获取模板图片
BufferedImage buffImg = ImageIO.read(resource.getInputStream());
// 开启画图
Graphics2D graphics = buffImg.createGraphics();
Font qrNameFont = Font.createFont(Font.TRUETYPE_FONT, fontResource.getInputStream());
graphics.setFont(qrNameFont);
//接下来就是操作graphics画图 但是字总写不出来
一番抓耳挠腮之后。度娘了半天的我决定看官方文档
public static Font createFont(int fontFormat, InputStream fontStream) throws FontFormatException, IOExceptionReturns a new
Fontusing the specified font type and input data. The newFontis created with a point size of 1 and stylePLAIN. This base font can then be used with thederiveFontmethods in this class to derive newFontobjects with varying sizes, styles, transforms and font features. This method does not close theInputStream.To make the
Fontavailable to Font constructors the returnedFontmust be registered in theGraphicsEnviromentby callingregisterFont(Font).
为了让字体可用必须注册。。。。。。。原因找到了,接下来看GraphicsEnviroment 的registerFont方法
可以看到整个GraphicsEnviroment 中有创建 GraphicsEnviroment 对象的getLocalGraphicsEnvironment()方法
还有一个创建Graphics2D对象的createGraphics(java.awt.image.BufferedImage)方法。
好了 流程大概就清楚了
首先创建GraphicsEnviroment 对象 再把创建的字体registerFont进GraphicsEnviroment 对象 最终通过GraphicsEnviroment创建Graphics2D对象 用这个Graphics2D对象才有创建的字体
代码改写如下
//模板
ClassPathResource resource = new ClassPathResource("template/template1.png");
//字体
ClassPathResource fontResource = new ClassPathResource("font/simsun.ttf");
// 获取模板图片
BufferedImage buffImg = ImageIO.read(resource.getInputStream());
// 设置文字
Font font = Font.createFont(Font.TRUETYPE_FONT, fontResource.getInputStream());
设置字体
font = font.deriveFont(Font.BOLD, 64F);
Font multiFont = font.deriveFont(Font.BOLD, 60f);
Font finalfont = font.deriveFont(Font.PLAIN, 50f);
GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
localGraphicsEnvironment.registerFont(font);
localGraphicsEnvironment.registerFont(multiFont);
localGraphicsEnvironment.registerFont(finalfont);
// 开启画图
Graphics2D graphics = localGraphicsEnvironment.createGraphics(buffImg);
//设置字体
graphics.setFont(font);
//这里就是大小为64F的字体
graphics.setFont(multiFont);
//这里就是大小为60f的字体
graphics.setFont(finalfont);
//这里就是大小为50f的字体
好了 问题解决 还是要多看官方文档啊
本文介绍如何在Java项目中使用Font.createFont方法动态加载本地字体文件,解决项目上线后因服务器未安装字体而导致的中文乱码问题。文章详细讲解了字体注册到GraphicsEnvironment的步骤,并提供了代码示例。
1618

被折叠的 条评论
为什么被折叠?



