public static File generateUserAvatar(String letter) throws IOException {
log.info("生成头像名字:{}",letter);
int width = 100;
int height = 100;
// 创建画布
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = image.createGraphics();
// 抗锯齿
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 背景颜色(随机或固定)
Color backgroundColor = Color.CYAN; // 可替换为用户喜欢的颜色
graphics.setColor(backgroundColor);
graphics.fillOval(0, 0, width, height); // 圆形背景
// 字母颜色
graphics.setColor(Color.BLACK);
// 字体设置
Font font = new Font("微软雅黑", Font.BOLD, 40);
graphics.setFont(font);
// 计算字母居中位置
FontMetrics fontMetrics = graphics.getFontMetrics();
int x = (width - fontMetrics.stringWidth(letter)) / 2;
int y = (height - fontMetrics.getHeight()) / 2 + fontMetrics.getAscent();
// 绘制字母
graphics.drawString(letter, x, y);
graphics.dispose();
// 将图片转换为字节流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", baos);
InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
return inputStreamToFile(inputStream,"PNG");
}
public static File inputStreamToFile(InputStream inputStream, String suffix) throws IOException {
// 创建一个临时文件
File tempFile = File.createTempFile("temp", suffix);
tempFile.deleteOnExit(); // 程序结束时自动删除文件
// 使用try-with-resources语句确保FileOutputStream在完成后被正确关闭
try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
return tempFile;
}
public static void main(String[] args) {
String username = "第三方";
char firstLetter = username.charAt(0);
try {
File file=generateUserAvatar(String.valueOf(firstLetter));
Path targetPath = Paths.get("C:/out/image/avatar.png");
Files.move(file.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("头像生成成功!");
} catch (IOException e) {
e.printStackTrace();
}
}

06-21
704
704
08-08
3554
3554
10-16
280
280
12-29
1536
1536
06-20
3670
3670

被折叠的 条评论
为什么被折叠?



