生成个人章代码
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public static void main(String[] args) throws Exception {
//高度一定,宽度随字数而变化
String name = "李四";
int length = name.length();
int width = length * 30 + 15;
createImage2(name, new Font("宋体", Font.PLAIN, 30), new File("/Users/a1.png"), width, 50);
}
public static void createImage2(String str, Font font, File outFile, Integer width, Integer height) throws Exception { // 创建图片 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) image.getGraphics(); g.setClip(0, 0, width, height); g.setColor(Color.WHITE); // 先用黑色填充整张图片,也就是背景 g.fillRect(0, 0, width, height); //透明 image = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT); g.dispose(); g = image.createGraphics(); g.setColor(Color.red); //画框框 g.setColor(new Color(220, 240, 240)); g.setStroke(new BasicStroke(3.0f)); // 画横线 g.setColor(Color.red); g.drawLine(0, 0, width, 0); g.drawLine(0, height, width, height); // 画竖线 g.setColor(Color.red); g.drawLine(0, 0, 0, height); g.drawLine(width, 0, width, height); // 设置画笔字体 g.setFont(font); /** 用于获得垂直居中y */ FontMetrics fm = g.getFontMetrics(font); int ascent = fm.getAscent(); int descent = fm.getDescent(); int left = str.length() * 30; int y = (height - (ascent + descent)) / 2 + ascent; int x = (width - left) / 2; // 画出字符串 g.drawString(str, x, y); g.dispose(); // 输出png图片 ImageIO.write(image, "png", outFile); }
简易的红色框+文字生成图片功能