给图片加上水印

本文介绍如何使用Java进行图像处理,包括将文本水印添加到图片上,并调整JPEG图像的质量。首先读取文件为BufferedImage格式,然后通过Graphics2D在图片上绘制透明的文本水印,最后保存JPEG格式的图片并设置质量参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static void saveJPEGImage(BufferedImage bi, File outputFile,
            int quality) throws FileNotFoundException, IOException {
        BufferedOutputStream out = new BufferedOutputStream(
                new FileOutputStream(outputFile));

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);

        param.setQuality(quality / 100.0f, false);

        encoder.setJPEGEncodeParam(param);

        encoder.encode(bi);

        out.close();
    }

 

 

public static void watermarkImage(File imageFile, String message)
            throws FileNotFoundException, IOException {

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                imageFile));

        BufferedImage bi = ImageIO.read(bis);

        Graphics2D g = (Graphics2D) bi.getGraphics();

        int width = bi.getWidth();

        int height = bi.getHeight();

        Font myFont = new Font("Sans", Font.BOLD, 18);

        Rectangle2D bb = myFont.getStringBounds(message, g
                .getFontRenderContext());

        if (width < bb.getWidth() + 6 || height < bb.getHeight() + 20)
            return;

        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                (float) 0.5));

        int x = width - (int) bb.getWidth() - 3;

        int y = height - 10;

        g.setFont(myFont);

        g.setColor(Color.lightGray);

        g.drawString(message, x, y);

        saveJPEGImage(bi, imageFile, 100);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值