功能说明:解决将文字和图片镶嵌到另外一张图片上,生成的图片中文乱码。
1、拼接两张图片和文字
package com.qg;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public class QRCodeTest {
public static String overlapImage(String backgroundPath, String qrCodePath, String deptMessage, String myMessage, String outPutPath) {
try {
//设置图片大小
BufferedImage background = resizeImage(690, 961, ImageIO.read(new File(backgroundPath)));
//设置二维码大小
BufferedImage qrCode = resizeImage(206, 206, ImageIO.read(new File(qrCodePath)));
//在背景图片中添加入需要写入的信息,
Graphics2D g = background.createGraphics();
g.setColor(Color.white);
g.setFont(new Font("PingFangSC-Medium", Font.PLAIN, 20));
//设置文字位置
g.drawString(deptMessage, 50, 850);
g.drawString(myMessage, 400, 850);
//在背景图片上添加二维码图片
//设置二维码位置
g.drawImage(qrCode, 249, 378, qrCode.getWidth(), qrCode.getHeight(), null);
g.dispose();
ImageIO.write(background, "png", new File(outPutPath));
} catch (Exception e) {
e.printStackTrace();
System.out.println("出异常了!!!");
System.out.println(e.getMessage());
}
return outPutPath;
}
public static BufferedImage resizeImage(int x, int y, BufferedImage bfi) {
BufferedImage bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
bufferedImage.getGraphics().drawImage(
bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);
return bufferedImage;
}
public static void main(String[] args) {
String backgroundPath="C:\\Users\\96109\\Desktop/background.png";
String qrCodePath="C:\\Users\\96109\\Desktop/xxx.png";
String deptMessage="城东格";
String myMessage="xxx";
String outPutPath="C:\\Users\\96109\\Desktop/xxx.png";
QRCodeTest.overlapImage(backgroundPath,qrCodePath,deptMessage,myMessage,outPutPath);
System.out.println("执行成功!");
}
}
2、以上代码文字用的是:PingFangSC-Medium。但是Linux环境中不存在字体,需要将字体安装到Linux环境中去
3、下载字体PingFangSC-Medium.ttf 。如果本地有就去C:\Windows\Fonts 下找到字体
4、fc-list 查询Linux中已安装的字体
5、 mkdir -p /usr/share/fonts/my_fonts 创建目录
6、将PingFangSC-Medium.ttf拷贝到/usr/share/fonts/my_fonts路径下
7、yum -y install fontconfig 安装字体(安装过程中会有提示让你确认 输入y即可)
8、fc-list :lang=zh 查看Linux的中文字体
9、重新生成图片解决中文乱码