需求场景:
对接一卡通打印机,然后需要将系统中存储的用户照片和卡面照片合成一张照片传递给前端,由前端进行打印,卡面照片由于显示头像部分为不规则部分,所以下面的工具类把卡的照片作为了前景图片,用户照片作为了背景图片
需要用到的相关类
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
初步工具类(参数写死):
public class ImageCl {
public static String cltp() {
try {
// 读取背景图片和要叠加的图片
BufferedImage background = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\ren.png"));
BufferedImage foreground = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\微信图片_20240509164414.png"));
// 创建一个新的BufferedImage,大小与背景图片相同(假设)
BufferedImage combined = new BufferedImage(638, 1010, BufferedImage.TYPE_INT_ARGB);
// 获取Graphics2D对象以在combined上绘制
Graphics2D g2d = combined.createGraphics();
// 绘制背景图片(这里假设你已经知道了正确的裁剪区域)
g2d.drawImage(background, 78, 154, 561, 880, 0, 0, 490, 726, null);
// 绘制前景图片
g2d.drawImage(foreground, 0, 0, 638, 1010, 0, 0, 638, 1010, null);
// 加载微软雅黑字体文件(确保路径正确)
File fontFile = new File("C:\\Windows\\Fonts\\msyh.ttc"); // 微软雅黑字体文件路径
Font baseFont = Font.createFont(Font.TRUETYPE_FONT, fontFile);
// 设置粗体字体
Font boldFont = baseFont.deriveFont(Font.BOLD, 70); // 粗体,字号36
// 设置常规字体(如果需要的话,可以指定不同的字号)
Font regularFont = baseFont.deriveFont(Font.PLAIN, 30); // 常规,字号36
// ... 绘制背景图片和前景图片 ...
String text1 = "李甲";
// 设置Graphics2D的字体和颜色来绘制第一段文本(粗体)
g2d.setFont(boldFont);
g2d.setColor(Color.WHITE); // 白色文本
g2d.drawString(text1, 270, 700);
// 设置第二段文本的颜色和常规字体
g2d.setColor(new Color(0xeb, 0x61, 0x00)); // #eb6100
g2d.setFont(regularFont); // 设置为常规字体
// 绘制第二段文本(在第一段文本下方34像素位置)
String text2 = "123456781";
FontMetrics fm = g2d.getFontMetrics();
int text2Y = 647 + fm.getHeight() + 80; // 文本高度加间距
g2d.drawString(text2, 270, text2Y); // 注意这里的X坐标稍微移动了一点,以匹配粗体文本的宽度(如果需要)
// 释放Graphics2D资源
g2d.dispose();
// 保存合成后的图片
ImageIO.write(combined, "png", new File("C:\\Users\\Administrator\\Desktop\\combined_with_text.png"));
} catch (IOException | FontFormatException e) {
e.printStackTrace();
}
return "";
}
}
有了上面的初步工具类我们就可以进行参数替换了(将写死的参数替换成调用方法时传递的参数)因为只是需要把写死的参数替换这面就不进行替换了如果有需要可以自行替换😄
拓展:
1、当读取的前景图片和背景照片为base64时只需要加上以下代码即可
String base64Background = dbUser.getNowPic(); // 这里是你的背景图片的Base64编码字符串
//前景图片和背景图片的获取方式一样所以此处省略
byte[] backgroundBytes = java.util.Base64.getDecoder().decode(base64Background);
try (ByteArrayInputStream backgroundStream = new ByteArrayInputStream(backgroundBytes);
//前景图片和背景图片的获取方式一样所以此处省略
) {
//其他不变代码
}catch (IOException | FontFormatException e)
{ e.printStackTrace();
}
2、当要求返回为Base64字符串的话也很简单
// 将BufferedImage直接转换为Base64,而不是先保存为文件
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(combined, "png", baos);
byte[] imageBytes = baos.toByteArray();
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
System.out.println("Base64编码的图片字符串: " + base64Image);
至此一个很简单的图片合成代码就结束了,大神勿喷🎉️