java通过BufferedImage合并图片并在合并后的图片上写字

public static void main(String[] args) throws IOException {
        // 读取商品图
        BufferedImage productImg = ImageIO.read(new File("/Users/Documents/uploadfile/20240402211356308.jpeg"));
        int widthProduct = productImg.getWidth();
        int heightProduct = productImg.getHeight();

        // 读取小程序码
        BufferedImage appletImg = ImageIO.read(new File("/Users/Documents/uploadfile/wx.png"));
        int widthApplet = appletImg.getWidth();
        int heightApplet = appletImg.getHeight();

        // 创建合并图片
        int width = Math.max(widthProduct, widthApplet);
        int height = heightProduct + heightApplet + 40;
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 获取画笔
        Graphics2D g2d = result.createGraphics();
        g2d.setBackground(Color.WHITE);     // 设置背景色
        g2d.clearRect(0, 0, width, height);  // 清除图片当前内容,应用背景颜色

        // 设置字体
        Font font = new Font("宋体",  Font.BOLD, 50);
        g2d.setFont(font);
        g2d.setColor(Color.RED);    // 设置字体颜色

        // 获取字体行高
        int heigthFont = g2d.getFontMetrics().getHeight();

        // 绘制商品图片
        g2d.drawImage(productImg, 0 ,0 , null);

        // 绘制商品名称
        g2d.drawString("2024最新款MacBook", 0, heightProduct + heigthFont);

        // 绘制小程序码
        g2d.drawImage(appletImg, width-widthApplet, height - heightApplet, null);

        // 保存合并图片
        ImageIO.write(result, "jpg", new File("/Users/Documents/uploadfile/result.jpg"));

        // 释放图形上下文使用的系统资源
        g2d.dispose();
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值