最近接了一个需求,需求是给了一张图片,需要向图片当中插入文字,具体文字插入什么根据程序来定,例如下图:
需要对成果名称,完成单位,完成人等进行填充文字。
打开画图工具,然后选择文本
然后我们利用文本框框来测出他的边距,有了边距我们才能定位写文字的位置,宽度1105
高度530
实现出来的代码如下:
@GetMapping("/downImg")
public void downImg(HttpServletResponse response) {
downloadService.downImg(response);
}
如下代码当中除了IoUtil使用的是hutool的工具类外,其他的均属于Java基础类(不需要引入其他依赖就能使用的)。
public void downImg(HttpServletResponse response) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("templates/中医药科技成果登记证书.png");
Image src = ImageIO.read(inputStream);
// 获取图片的高和宽
int wideth = src.getWidth(null);
int height = src.getHeight(null);
// 新增一个图片缓冲
BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();
g.drawImage(src, 0, 0, wideth, height, null);
// 设置字体颜色(颜色也可以直接new定义rgba,例如new Color(17, 16, 44))
g.setColor(Color.BLACK);
// size字体大小,Font.BOLD字体加粗
g.setFont(new Font("宋体", Font.BOLD, 50));
// 写入成果名称,由宽度减去我们测的宽度度,就等于要开始写的位置
g.drawString("测试测试", wideth - 1105, height - 530);
// 释放资源
g.dispose();
responseSetting(response, "中医药科技", ".png", "image/png");
outputStream = response.getOutputStream();
ImageIO.write(image, "png", outputStream);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IoUtil.close(inputStream);
IoUtil.close(outputStream);
}
}
测试:
关于Font类:public Font(String name, int style, int size)
- name:字体,中文字体名:宋体,楷体,黑体等;英文字体名:Arial,Times New Roman等;
- style:风格
- Font.PLAIN (普通)
- Font.BOLD (加粗)
- Font.ITALIC (斜体)
- Font.BOLD+Font.ITALIC(斜体加粗)
- size:文字大小