java生成名字首字母头像

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();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值