/**
* 二维码添加文字
* @param args
* @throws WriterException
*/
public static BufferedImage addBottomText(BufferedImage image,String note){
BufferedImage outImage = new BufferedImage(430, 480, BufferedImage.TYPE_INT_BGR);
int width = image.getWidth();
int height = image.getHeight();
if (!MyStringUtil.isNullOrEmpty(note)) {
// 新的图片,把带logo的二维码下面加上文字
Graphics2D outg = outImage.createGraphics();
// 画二维码到新的面板
outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
// 画文字到新的面板
outg.setColor(Color.white);
outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号
int strWidth = outg.getFontMetrics().stringWidth(note);
if (strWidth > 399) {
// //长度过长就截取前面部分
// 长度过长就换行
String note1 = note.substring(0, note.length() / 2);
String note2 = note.substring(note.length() / 2, note.length());
int strWidth1 = outg.getFontMetrics().stringWidth(note1);
int strWidth2 = outg.getFontMetrics().stringWidth(note2);
outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
BufferedImage outImage2 = new BufferedImage(400, 480, BufferedImage.TYPE_INT_BGR);
Graphics2D outg2 = outImage2.createGraphics();
outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
outg2.setColor(Color.BLACK);
outg2.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
outg2.drawString(note2, 200 - strWidth2 / 2,
outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
outg2.dispose();
outImage2.flush();
outImage = outImage2;
} else {
outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字
}
outg.dispose();
}
return outImage;
}
这是一个二维码底部添加中文的方法,本地运行没问题,到linux上就乱码了
解决方案:
1.找到本地windows下对应的中文字体,比如宋体,楷体
C:\Windows\Fonts
2.把中文字体文件复制到linux系统/usr/share/fonts下,随便新建一个文件夹来装windows中的字体文件
3.先执行
yum install mkfontscale
yum install fontconfig
4.在新建字体文件夹下执行命令mkfontscale && mkfontdir && fc-cache -fv
5.刷新字体缓存
fc-cache -fv
6.查看字体列表
fc-list
7.重启你的java程序