系统在服务器上发布之后,图形验证码乱码的问题

应用系统在linux服务器上部署启动,然后刷新页面,验证码图形出现乱码:https://i-blog.csdnimg.cn/blog_migrate/87a41ffcb070a846537ab66eda39050f.png

附上代码:

// 设置页面不缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// response.setContentType("image/png");

// 在内存中创建图象
final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
final Graphics2D graphics = (Graphics2D) image.getGraphics();

// 设定背景颜色
graphics.setColor(Color.WHITE); // ---1
graphics.fillRect(0, 0, width, height);
// 设定边框颜色
//		graphics.setColor(getRandColor(100, 200)); // ---2
graphics.drawRect(0, 0, width - 1, height - 1);

final Random random = new Random();
// 随机产生干扰线,使图象中的认证码不易被其它程序探测到
for (int i = 0; i < count; i++) {
	graphics.setColor(getRandColor(150, 200)); // ---3

	final int x = random.nextInt(width - lineWidth - 1) + 1; // 保证画在边框之内
	final int y = random.nextInt(height - lineWidth - 1) + 1;
	final int xl = random.nextInt(lineWidth);
	final int yl = random.nextInt(lineWidth);
	graphics.drawLine(x, y, x + xl, y + yl);
}

// 取随机产生的认证码(4位数字)
final String resultCode = exctractRandCode();
for (int i = 0; i < resultCode.length(); i++) {
	// 将认证码显示到图象中,调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
	// graphics.setColor(new Color(20 + random.nextInt(130), 20 + random
	// .nextInt(130), 20 + random.nextInt(130)));

    // 设置字体颜色
	graphics.setColor(Color.BLACK);
    // 设置字体样式
//			graphics.setFont(new Font("Arial Black", Font.ITALIC, 18));
    graphics.setFont(new Font("Times New Roman", Font.BOLD, 24));
    // 设置字符,字符间距,上边距
	graphics.drawString(String.valueOf(resultCode.charAt(i)), (23 * i) + 8, 26);
}

// 将认证码存入SESSION
request.getSession().setAttribute(SESSION_KEY_OF_RAND_CODE, resultCode);
// 图象生效
graphics.dispose();

// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());

运行服务之后,通过日志,发现验证码生成输出正常。查看代码,发现Graphics2D在生成文本的时候,其实调用了Font组件

进入font源码:

系统代码中使用的字体是“Times New Roman”,本地测试验证码图片没问题,是因为window平台是有该字体的,查看对应服务器上的系统字体:

https://i-blog.csdnimg.cn/blog_migrate/631f156354ad8d9af32d756ea7b57d78.png

以及系统的字体列表:

https://i-blog.csdnimg.cn/blog_migrate/4765ac395d75031d013c84496aed99db.png

发现并没有我们需要的字体,于是基本可以确定问题点是出在系统字体上面。

解决方法很直接,就是直接到windows的字体目录下https://i-blog.csdnimg.cn/blog_migrate/122771e802999168bf09381ad5985790.png

选择该字体,直接上传到服务器的字体文件目录下,可以创建自定义目录:(我是新建了Times New Roman的目录,将拷贝出来的字体放在了此目录下)

然后利用命令:fc-cache 重新载入字体配置,清除字体缓存。然后重启项目,发现一切ok

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值