根据图片模板生成图片
背景
根据提供的证书模板生成对应证书,证书内容有,姓名,身份证号,证书名称,证书编号,发证日期
根据用户达成的条件自动生成证书图片。
证书模板如下(原图):
流程简介
根据模板生成图片的流程如下
- 读取 图片模板
- 确定 需要替换内容的坐标
- 确定需要替换的内容
- 生成图片并保存
下面分别按上述步骤介绍方法
- 读取图片模板
//将图片链接转化为可操作的 Image对象
private BufferedImage readImageFromUrl(String template) {
try {
URL url = new URL(template);
return ImageIO.read(url);
} catch (IOException e) {
}
return null;
}
//将本地图片转化为可操作的 Image对象
private BufferedImage readImageFromPath(String template) {
try(FileInputStream input = new FileInputStream(new File(template))) {
return ImageIO.read(input);
} catch (IOException e) {
}
return null;
}
- 确定需要替换的内容坐标
如果有设计稿的话,直接在设计稿上可以清楚的看到内容坐标。
如果没有设计稿,下面推荐一个在线PS网站,将图片托进来也可以清楚的获取需要替换的内容坐标
注意:画布是坐标原点在左上角
所以姓名所在的位置坐标应该是 (578,832)
- 确定需要替换的内容并替换
确定好替换的内容,包括字体大小,颜色等
Graphics2D g = sourceImage.createGraphics();
g.setColor(Color.RED);//设置画笔颜色
g.setFont(new Font("宋体",Font.PLAIN,58));// 更改字体、样式和大小
//替换内容
g.drawString("张三", 578, 832);
注意:画图时是从左下脚开始画的,所以drawString方法填入的坐标点,是准备填入内容的的左下角的位置
如下图所示:
4. 生成新的图片
将Image对象转为文件
//图片生成到本地
File outputImageFile = new File("output_image.jpg"); // 输出图片文件路径
ImageIO.write(modifiedImage, "jpg", outputImageFile);
//或者写入输出流,然后上传到服务器
try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()){
ImageIO.write(newImage,ext,outputStream);
}catch (IOException e){
}
代码实现
这里做了简单的代码抽象
抽象一些辅助类:用来存储模板信息,替换位置,以及字体,内容等
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class PicWithParams {
//模板地址
private String picTemplate;
//替换的参数列表