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

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

码农世界 2024-05-23 前端 75 次浏览 0个评论
Python
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;
    }
}

转载请注明来自码农世界,本文标题:《JAVA 实现上传图片添加文字水印或图片水印》

百度分享代码,如果开启HTTPS请参考李洋个人博客
每一天,每一秒,你所做的决定都会改变你的人生!

发表评论

快捷回复:

评论列表 (暂无评论,75人围观)参与讨论

还没有评论,来说两句吧...

Top