import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
public class ImageUtil {
public static Map<String, Object> getImageCode(int width, int height) {
Map<String,Object> returnMap = new HashMap<>();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 设定背景色
g.setColor(new Color(236, 236, 240));
g.fillRect(0, 0, width, height);
//设定字体
g.setFont(new Font("随便定义字体", Font.BOLD, 14));
g.setColor(new Color(82, 84, 87));
//取随机产生的码
String code = PasswordUtil.generateVerificationCode(5);
// String code = "GZTWM";
//4代表4位验证码,如果要生成更多位的认证码,则加大数值
FontMetrics fm = g.getFontMetrics();
g.drawString(code,(width-fm.stringWidth(code))/2, 15);
// 释放图形上下文
g.dispose();
try {
returnMap.put("image",getBufferedImageToBase64(image,"jpg"));
} catch (IOException e) {
e.printStackTrace();
}
returnMap.put("code",code);
return returnMap;
}
/**
* BufferedImage转成 base64
* @param bufferedImage
* @param imageFormatName
* @return
*/
public static String getBufferedImageToBase64(BufferedImage bufferedImage,String imageFormatName) throws IOException {
if(StringUtils.isBlank(imageFormatName)){
imageFormatName = "png";
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, imageFormatName, stream);
String s = Base64.getEncoder().encodeToString(stream.toByteArray());
return s;
}
}