- 上代码
package com.example.demotest.controller;/*** @Author shaolin* @Date 2024-10-08 10:11**/import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;public class TextToImage {public static void main(String[] args) throws IOException {ColorModel cm = ColorModel.getRGBdefault();// 指定图片宽与高WritableRaster wr = cm.createCompatibleWritableRaster(200, 50);BufferedImage bi = new BufferedImage(cm, wr, cm.isAlphaPremultiplied(), null);Graphics2D graphics = bi.createGraphics();// 设置文字graphics.setFont(new Font(null, Font.PLAIN, 25));// 设置颜色graphics.setColor(Color.GRAY);// 指定插入文字及其位置graphics.drawString("雷少林", 60, 35);graphics.dispose();ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();ImageIO.write(bi, "png", byteArrayOutputStream);byte[] byteArray = byteArrayOutputStream.toByteArray();System.out.println(Base64.getEncoder().encodeToString(byteArray));}
}
如果改成方法的话, 把图片宽与高 ,以及指定插入文字及其位置的俩参数以及生成的文字,都改为前端传值
- 如果是想后端把除中文名称外的参数写死的话,可以 把打印的base64输入到下面的地址的输入框里
地址: https://www.uutils.com/image/base64_to_image.htm
如图所示:
然后点击下载,查看效果