JAVA 实现上传图片添加文字水印或图片水印

package cn.jiyun.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;

public class TransparentWatermark {

    // 水印字体
    private static final Font FONT = new Font("微软雅黑", Font.PLAIN, 14);

    // 透明度
    private static final AlphaComposite COMPOSITE = AlphaComposite
            .getInstance(AlphaComposite.SRC_OVER, 0.6f);

    // 水印之间的间隔
    private static final int X_MOVE = 150;

    // 水印之间的间隔
    private static final int Y_MOVE = 200;


    public static void main(String[] args) {
        String url = "https://****/2024/05/22/b492358e1d0f4195ab387712f26b1103.jpeg";
        String local = "D:\\upload\\watermarked.png";
//        TransparentWatermark.addWatermark(url);

        TransparentWatermark.markWithContent(local, FONT, Color.darkGray, "测试水印文字",
                    "D:\\upload\\watermarked2.png");
    }

    /**
     * 添加logo水印
     * @param original
     */
    public static void  addWatermark(String original) {
        // 读取原图片
        BufferedImage image = getRemoteBufferedImage(original);
//        try {
//            image = ImageIO.read(new File(original));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        // 获取图片的宽度和高度
        int width = image.getWidth();
        int height = image.getHeight();
        // 创建一个图片缓存对象
        BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取图片的画笔
        Graphics2D g = newImage.createGraphics();
        // 将原图片绘制到缓存图片上
        g.drawImage(image, 0, 0, width, height, null);
        // 读取水印图片
        BufferedImage watermark = null;
        try {
            watermark = ImageIO.read(new File("D:\\upload\\logo.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 获取水印图片的宽度和高度
        int wmWidth = watermark.getWidth();
        int wmHeight = watermark.getHeight();
        // 设置水印图片的透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
        // 绘制水印图片
//        g.drawImage(watermark, width - wmWidth - 10, height - wmHeight - 10, wmWidth, wmHeight, null);
        g.drawImage(watermark, width - 60, height - 60, 60, 60, null);
        g.drawImage(watermark, width - 0, height - 60, 60, 60, null);
        // 释放图形上下文使用的系统资源
        g.dispose();
        // 保存带水印的图片
        try {
            ImageIO.write(newImage, "png", new File("D:\\upload\\watermarked.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取远程网络图片信息
     * @param imageURL
     * @return
     */
    public static BufferedImage getRemoteBufferedImage(String imageURL) {
        URL url = null;
        InputStream is = null;
        BufferedImage bufferedImage = null;
        try {
            url = new URL(imageURL);
            is = url.openStream();
            bufferedImage = ImageIO.read(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            System.out.println("imageURL: " + imageURL + ",无效!");
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("imageURL: " + imageURL + ",读取失败!");
            return null;
        } finally {
            try {
                if (is!=null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("imageURL: " + imageURL + ",流关闭异常!");
                return null;
            }
        }
        return bufferedImage;
    }


    /**
     * 打水印(文字)
     *
     * @param srcImgPath       源文件地址
     * @param font             字体
     * @param markContentColor 水印颜色
     * @param waterMarkContent 水印内容
     * @param outImgPath       输出文件的地址
     */
    public static void markWithContent(String srcImgPath, Font font, Color markContentColor,
                                       String waterMarkContent,
                                       String outImgPath) {
        FileOutputStream fos = null;
        try {
            // 读取原图片信息
            File srcFile = new File(srcImgPath);
            File outFile = new File(outImgPath);
            BufferedImage srcImg = ImageIO.read(srcFile);

            // 图片宽、高
            int imgWidth = srcImg.getWidth();
            int imgHeight = srcImg.getHeight();

            // 图片缓存
            BufferedImage bufImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

            // 创建绘图工具
            Graphics2D graphics = bufImg.createGraphics();

            // 画入原始图像
            graphics.drawImage(srcImg, 0, 0, imgWidth, imgHeight, null);

            // 设置水印颜色
            graphics.setColor(markContentColor);

            // 设置水印透明度
            graphics.setComposite(COMPOSITE);

            // 设置倾斜角度
            graphics.rotate(Math.toRadians(-35), (double) bufImg.getWidth() / 2,
                    (double) bufImg.getHeight() / 2);

            font = new Font(null, Font.PLAIN, 28);
            // 设置水印字体
            graphics.setFont(font);

            // 消除java.awt.Font字体的锯齿
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            int xCoordinate = -imgWidth / 2, yCoordinate;
            // 字体长度
            int markWidth = FONT.getSize() * getTextLength(waterMarkContent);
            // 字体高度
            int markHeight = FONT.getSize();

            // 循环添加水印
            while (xCoordinate < imgWidth * 1.5) {
                yCoordinate = -imgHeight / 2;
                while (yCoordinate < imgHeight * 1.5) {
                    graphics.drawString(waterMarkContent, xCoordinate, yCoordinate);
                    yCoordinate += markHeight + Y_MOVE;
                }
                xCoordinate += markWidth + X_MOVE;
            }

            // 释放画图工具
            graphics.dispose();

            // 输出图片
            fos = new FileOutputStream(outFile);
            ImageIO.write(bufImg, "jpg", fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    //计算水印文本长度
    //1、中文长度即文本长度 2、英文长度为文本长度二分之一
    public static int getTextLength(String text) {
        //水印文字长度
        int length = text.length();

        for (int i = 0; i < text.length(); i++) {
            String s = String.valueOf(text.charAt(i));
            if (s.getBytes().length > 1) {
                length++;
            }
        }
        length = length % 2 == 0 ? length / 2 : length / 2 + 1;
        return length;
    }


}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java可以使用Java2D API来实现图片文字水印。下面是一个简单的示例代码: ```java import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class ImageWatermark { public static void main(String[] args) throws IOException { // 读取原始图片 BufferedImage image = ImageIO.read(new File("original.jpg")); // 创建一个空白的图片,大小和原始图片一样 BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); // 获取图片的Graphics2D对象 Graphics2D g = result.createGraphics(); // 将原始图片绘制到空白图片上 g.drawImage(image, 0, 0, null); // 设置水印文字的相关属性 String text = "Hello, world!"; Font font = new Font("Arial", Font.BOLD, 36); Color color = Color.WHITE; // 绘制水印文字 g.setFont(font); g.setColor(color); int x = (image.getWidth() - g.getFontMetrics().stringWidth(text)) / 2; int y = image.getHeight() / 2; g.drawString(text, x, y); // 保存水印图片 ImageIO.write(result, "jpg", new File("watermark.jpg")); } } ``` 在这个示例代码中,我们首先读取原始图片,然后创建一个空白的图片,大小和原始图片一样。接着,我们获取空白图片的Graphics2D对象,将原始图片绘制到空白图片上。然后,我们设置水印文字的相关属性,包括文字内容、字体和颜色,并在空白图片上绘制水印文字。最后,我们将水印图片保存到文件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员奋斗者GO

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值