JAVA读取本地字体 您所在的位置:网站首页 验证码字体文件是什么 JAVA读取本地字体

JAVA读取本地字体

2024-06-17 02:17| 来源: 网络整理| 查看: 265

一、问题背景

项目一直部署在阿里云上,一直正常运行。最近换新环境之后登陆界面的验证码不显示,后台报错:

java.lang.NullPointerException at sun.awt.FontConfiguration.getVersion 二、原因分析

代码没变过,一样的包,那只能从部署环境找问题。仔细对比了现在和以前的环境,发现之前用的是JDK1.8,现在用的是OpenJDK8。查了一些资料,证实了一件事情——OpenJDK不支持awt包下的字体。

三、解决办法

解决办法有两个,要么改服务器环境,要么改自己的代码。

1、服务器配置

在服务器上安装FontConfig组件:

yum install fontconfig fc-cache --force 2、修改项目代码

上面的方法看起来很好用,但是不解决实际问题,换一个服务器就得执行一回,最终决定还是直接改项目里的代码,要么直接用服务器上有的字体文件,要么在项目里引一个字体文件进去。

2.1 创建项目

创建一个springBoot项目。

2.2  找字体

windows系统:打开C:\Windows\Fonts 目录,找个喜欢的字体,复制到项目里。

2.3  代码引用 import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.core.io.ClassPathResource; import java.awt.*; import java.io.InputStream; @SpringBootApplication public class AwtApplication { private static Font loadFontResource() throws Exception { InputStream resourceAsStream = null; try { ClassPathResource classPathResource = new ClassPathResource("static/font/STXIHEI.TTF"); resourceAsStream =classPathResource.getInputStream(); Font font = Font.createFont(Font.TRUETYPE_FONT, resourceAsStream); Font targetFont = font.deriveFont(Font.PLAIN); return targetFont; } catch (FontFormatException e) { e.printStackTrace(); return null; } } public static void main(String[] args) { SpringApplication.run(AwtApplication.class, args); try { Font font = loadFontResource(); System.out.println("字体名称:"+font.getFontName()); }catch (Exception e){ e.printStackTrace(); } } } 四、鸣谢

https://blog.csdn.net/lw5885799/article/details/102727697



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有