背景
如上图,需要使用Java生成一个图片, 并以base64编码的形式返回给前端展示。
使用Graphics2D类,来进行画图,其中需要画方框、原型、插入图标、写入文字等,同时需要设置透明度等细节点
环境:Jdk17,springboot2.7.13
代码如下
有详细的注释
package com.demo;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ThreadLocalRandom;
/**
* <p>
* 功能描述:
* </p>
*
* @author MILLA
* @version 1.0
* @since 2024/06/24 9:14
*/
@Slf4j
public class ImageDemo {
/**
* 每个div的高度
*/
private static final int LINE_HEIGHT = 80;
private static final double COLOR_WIDTH = 0.7;
/**
* 处方笺图片宽
*/
private static final int PIC_WIDTH = 1200;
/**
* 顶部与底部留白
*/
private static final int MARGIN_Y = 52;
/**
* 左右留白
*/
private static final int MARGIN_X = 50;
/**
* 生成图片后缀
*/
private static final String FILE_SUFFIX = ".jpg";
public static void main(String[] args) throws Exception {
List<Object> objects = Lists.newArrayList(1, 2, 3, 4, 5, 6);
String base64 = new ImageDemo().getImage(objects);
System.out.println(base64);
}
/**
* 初始化
*
* @param image 画布
* @param graphics 画笔
*/
private void initiation(BufferedImage image, Graphics2D graphics) {
int width = image.getWidth();
int height = image.getHeight();
graphics.setClip(0, 0, width, height);
// 设置画笔颜色
graphics.setColor(Color.white);
// 绘制背景
graphics.fillRect(0, 0, width, height);
// 设置抗锯齿
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
private String getImage(List<Object> objects) throws IOException {
//读取图标流
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("static/icon.png");
BufferedImage avatar = ImageIO.read(stream);
// 新建图片
BufferedImage image = new BufferedImage(PIC_WIDTH, objects.size() * LINE_HEIGHT + MARGIN_Y * 2, BufferedImage.TYPE_INT_BGR);
// 创建画笔
Graphics2D graphics = image.createGraphics();
// 初始化背景色
initiation(image, graphics);
// 定义margin
Margin margin = new Margin(MARGIN_Y, MARGIN_Y, MARGIN_X, MARGIN_X);
// 初始化坐标
Point point = new Point(margin.getLeft