Java给图片添加文字和图片水印

**

最近工作上有个需求,动态生成一张图片,具体来说就是基于模版图片动态添加文字和图片(文字内容不同,图片数目不同),其中文字大小不全一样,且对位置有所要求。

实现如下
**

public class Graphics2DUtil {
    private static final String FONT_FAMILY = "楷体";
    private static final String CERTIFICATE_BASE_PATH = "D:\\vehicle\\uploadPath\\login-1.png";
    private static final String WATERMARK_IMAGE_PATH = "/src/main/resources/static/icon.png";

    public static void graphics2DDrawTest(String srcImgPath, String outPath) {
        try {
            BufferedImage targetImg = ImageIO.read(new File(srcImgPath));
            int imgWidth = targetImg.getWidth();
            int imgHeight = targetImg.getHeight();
            BufferedImage bufferedImage = new BufferedImage(imgWidth, imgHeight,
                    BufferedImage.TYPE_INT_BGR);
            Graphics2D g = bufferedImage.createGraphics();

            g.drawImage(targetImg, 0, 0, imgWidth, imgHeight, null);
            g.setColor(Color.BLACK);
            // 第一行文本字体大小为120,居中显示
            Font userNameFont = new Font(FONT_FAMILY, Font.PLAIN, 120);
            g.setFont(userNameFont);

            String userName = "10:02:30";
            int[] userNameSize = getContentSize(userNameFont, userName);

            int userNameLeftMargin = (imgWidth - userNameSize[0]) / 2;
            int userNameTopMargin = 150 + userNameSize[1];
            g.drawString(userName, userNameLeftMargin, userNameTopMargin);
            g.dispose();

            FileOutputStream outImgStream = new FileOutputStream(outPath);
            ImageIO.write(bufferedImage, "png", outImgStream);
            g.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文本的长度,字体大小不同,长度也不同
     *
     * @param font
     * @param content
     * @return
     */
    public static int[] getContentSize(Font font, String content) {
        int[] contentSize = new int[2];
        FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
        Rectangle rec = font.getStringBounds(content, frc).getBounds();
        contentSize[0] = (int) rec.getWidth();
        contentSize[1] = (int) rec.getHeight();
        return contentSize;
    }


    public static void main(String[] args) throws IOException {
        String projectPath = System.getProperty("user.dir");
        String srcImgPath = CERTIFICATE_BASE_PATH;
        String outPath = "D:\\vehicle\\uploadPath\\success.png";

        graphics2DDrawTest(srcImgPath, outPath);
    }

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值