Java生成base64文字图
什么是文字图
文字图是一种特别小的图片,图片内容是1-2个文字,常用来做默认头像默认Logo之类的图片。
前端展示文字图,可以直接用img标签的base64图片功能来展示,也可以要求后端提供存好的图片的url,
由于文字图非常小,建议直接给前端提供文字图的base64字符串,为后端节省存储压力
Java生成文字图的自定义工具类
package cn.ath.knowwikibackend.util;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AvatarBuildUtil {
private static Color getRandomColor() {
String[] beautifulColors =
new String[]{"114,101,230", "255,191,0", "0,162,174", "245,106,0", "24,144,255", "96,109,128"};
String[] color = beautifulColors[RandomUtil.randomInt(beautifulColors.length)].split(StrUtil.COMMA);
return new Color(Integer.parseInt(color[0]), Integer.parseInt(color[1]),
Integer.parseInt(color[2]));
}
private static boolean isChinese(String str) {
String regEx = "[\\u4e00-\\u9fa5]+";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.find();
}
private static BufferedImage generateWZTBufferedImage(String name){
int width = 100;
int height = 100;
int nameLength = name.length();
String nameWritten;
if (nameLength <= 2) {
nameWritten = name;
} else {
String first = StrUtil.sub(name, 0, 1);
if (isChinese(first)) {
nameWritten = name.substring(nameLength - 2);
} else {
nameWritten = StrUtil.sub(name, 0, 1).toUpperCase();
}
}
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) bufferedImage.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setBackground(getRandomColor());
g2.clearRect(0, 0, width, height);
g2.setPaint(Color.WHITE);
Font font;
if(nameWritten.length() >= 2) {
font = new Font("微软雅黑", Font.BOLD, 30);
g2.setFont(font);
String firstWritten = StrUtil.sub(nameWritten, 0, 1);
String secondWritten = StrUtil.sub(nameWritten, 0, 2);
if (isChinese(firstWritten) && isChinese(secondWritten)) {
g2.drawString(nameWritten, 20, 60);
}
else if (isChinese(firstWritten) && !isChinese(secondWritten)) {
g2.drawString(nameWritten, 27, 60);
} else {
nameWritten = nameWritten.substring(0,1);
}
}
if(nameWritten.length() == 1) {
if(isChinese(nameWritten)) {
font = new Font("微软雅黑", Font.PLAIN, 50);
g2.setFont(font);
g2.drawString(nameWritten, 25, 70);
} else {
font = new Font("微软雅黑", Font.PLAIN, 55);
g2.setFont(font);
g2.drawString(nameWritten.toUpperCase(), 33, 67);
}
}
return bufferedImage;
}
public static String generateWZTImgBase64(String name) {
BufferedImage bufferedImage = generateWZTBufferedImage(name);
return ImgUtil.toBase64DataUri(bufferedImage, "jpg");
}
public static File generateWZTImgTempFile(String name){
BufferedImage bufferedImage = generateWZTBufferedImage(name);
String tmpDirPath = FileUtil.getTmpDirPath();
File tempFile = new File(tmpDirPath
+ "/" + System.currentTimeMillis() + ".jpg");
try {
ImageIO.write(bufferedImage,"jpg",tempFile);
} catch (IOException e) {
e.printStackTrace();
}
return tempFile;
}
}
测试效果
@Test
void testWenZiTu() {
String base64 = AvatarBuildUtil.generateWZTImgBase64("张飞");
System.out.println(base64);
File file = AvatarBuildUtil.generateWZTImgTempFile("琳琅天");
System.out.println(file.getAbsolutePath());
}
data:image/jpg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCABkAGQDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL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v6ljXvDN74d+z/a5bd/P3bfKYnG3Gc5A9RWfc6fd2cMEtxbyRRzrujZlwGFe16npdjeTW97eQNObMO0cYG4EnH8Pc/LxXnXi3xfNqwfTlsvs8Ctk+en73I+v3f5+9cuBzCtiOWKjf+Z7eljpxmBpUOaTlb+Vb/echRRRXsnkhRRRQAUUUUAdF4Imt7fxRBPdTxQxxo53yuFAJUjqfrXUa54d0ea1v/EVrfSTyoTKPLlRo947cDp04zXFeHtHTXdVWxa5+zlkZlfZu5HOMZHbNdvrdta+GPAc2lfallnmbC5G0uSwJOMngAV4uNaWKhySfM7K3lc9fBq+GlzxXKru/nY0b/xNdWXhGw1gRQtLO0fmJg7cEEnHPt61D4t8T6loZtJ7GK1ls7hMh5EYnd16hhwQR+tNlj0K98G6ZbXmppDaqiPkuFd9oIIx9c9M9KoaXqGka7p134cu5wsULt9jmY4zGCdpBPcD8x+NedTo0177hdRbvp0e33HfUq1H7inZyStr1/4JwN9eSahfT3koVZJnLsEGACfSq9S3MSQ3MsUcyzIjELIoIDD1Gair6mKSirbHzUrtu+56x4m1i+sPD2m6tp8uMlC4IyrKy55H1A/OuW1zXrjxVo6NDpWHtmBuZkXdtBBxg9QDg5+grX8Matp2t+HD4f1SRY5FXYhZsb1zlSCe49Pb61Zmt7TwN4YvokuxNd3RPlZAVjkYHGTwOTmvnaShh5ezcL1FLTzT8z36jnXj7RT/AHbWvk0eYUUUV9IfPhRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQB//9k=
C:\Users\ADMINI~1\AppData\Local\Temp\1686130217116.jpg
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0d50b5c61737466b1b2ef77df4757e1f.png)