文件系列一 :本地文件·、网络文件添加水印

本文介绍了如何使用Java为本地和网络图片添加文字及图片水印,详细讲解了通过网络图片URL获取InputStream的方法。
摘要由CSDN通过智能技术生成

添加水印

本地图片、网络图片添加文字水印、图片水印

package com.utils;

import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 图片水印
 *
 * @author: hmm
 * @date: 2020/11/18 13:33
 */
public class WatermarkUtil {

    //TODO:*************************************************************** 本地图片 *********************************************************


    /**
     * 给图片添加图片水印、可设置水印图片旋转角度
     *
     * @param iconPath   水印图片路径
     * @param srcImgPath 源图片路径
     * @param targetPath 目标图片路径
     * @param degree     水印图片旋转角度
     * @param formatName 目标图片格式
     */
    public static void markImageByIcon(String iconPath, String srcImgPath, String targetPath, Integer degree, String formatName) {
        OutputStream os = null;
        try {

            Image srcImg = ImageIO.read(new File(srcImgPath));
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            int srcWidth = srcImg.getWidth(null);
            int srcHeight = srcImg.getHeight(null);
            // 1、得到画笔对象
            Graphics2D g = buffImg.createGraphics();

            // 2、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

            // 3、设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
            }

            // 4、水印图片的路径 水印图片一般为gif或者png的,这样可设置透明度
            ImageIcon imgIcon = new ImageIcon(iconPath);
            // 5、得到Image对象。
            Image img = imgIcon.getImage();
            int iconWidth = img.getWidth(null);
            int iconHeight = img.getHeight(null);
            if (iconWidth < 0 || iconHeight < 0) {
                System.out.println("无法获取到水印图片,请确认 " + iconPath + " 路径是否存在水印图片!!");
            }
            double dmarkWidth = srcWidth * 0.8;// 设置水印的宽度为图片宽度的0.4倍
            double dmarkHeight = dmarkWidth * ((double) iconWidth / (double) iconHeight);//强转为double计算宽高比例

            int imarkWidth = (int) dmarkWidth;
            int imarkHeight = (int) dmarkHeight;

            // 6、水印图片的位置
            int x = (srcWidth - imarkWidth) / 2;
            int y = (srcHeight - imarkHeight) / 2;

            g.drawImage(img, x, y, imarkWidth, imarkHeight, null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            // 7、释放资源
            g.dispose();
            // 8、生成图片
            os = new FileOutputStream(targetPath);
            ImageIO.write(buffImg, formatName, os);
            System.out.println("[添加水印]图片完成添加水印图片");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("[添加水印] Exception, message=" + e.getMessage());
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * @param logoText   水印文字
     * @param srcImgPath 源图片路径
     * @param targetPath 目标图片路径
     * @param degree     水印文字旋转角度
     * @param color      水印文字颜色
     * @param formatName 文件后缀格式
     */
    public static void markImageByText(String logoText, String srcImgPath, String targetPath, Integer degree, Color color, String formatName) {
        InputStream is = null;
        OutputStream os = null;
        try {
            // 1、源图片
            Image srcImg = ImageIO.read(new File(srcImgPath));
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
            // 4、设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree), buffImg.getWidth() / 4, buffImg.getHeight() / 4);
            }
            // 5、设置水印文字颜色
            g.setColor(color);
            // 6、设置水印文字Font
            g.setFont(new Font("宋体", Font.BOLD, buffImg.getHeight() / 6));
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
            // 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
//            g.drawString(logoText,  buffImg.getWidth()/2 , buffImg.getHeight()/2);
            g.drawString(logoText, buffImg.getWidth() / 4, buffImg.getHeight() / 4);
            // 9、释放资源
            g.dispose();
            // 10、生成图片
            os = new FileOutputStream(targetPath);
            ImageIO.write(buffImg, formatName, os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is)
                    is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * @param logoText   水印文字
     * @param srcImgPath 源图片路径
     * @param targetPath 目标图片路径
     * @param color      水印文字颜色
     * @param formatName 文件后缀格式
     */
    public static void markImageByText(String logoText, String srcImgPath, String targetPath, Color color, String formatName) {
        InputStream is = null;
        OutputStream os = null;
        try {
            // 1、源图片
            Image srcImg = ImageIO.read(new File(srcImgPath));
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

            // 5、设置水印文字颜色
            g.setColor(color);
            // 6、设置水印文字Font
            g.setFont(new Font("宋体", Font.BOLD, buffImg.getHeight() / 6));
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
            // 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
//            g.drawString(logoText,  buffImg.getWidth()/2 , buffImg.getHeight()/2);
            g.drawString(logoText, buffImg.getWidth() / 4, buffImg.getHeight() / 4);
            // 9、释放资源
            g.dispose();
            // 10、生成图片
            os = new FileOutputStream(targetPath);


            ImageIO.write(buffImg, formatName, os);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }




    //TODO:*************************************************************** 网络图片 *********************************************************

    /**
     * 给图片添加图片水印、可设置水印图片旋转角度
     *
     * @param iconPath   水印图片路径
     * @param srcImgPath 网络图片url
     * @param targetPath 目标图片路径
     * @param degree     水印图片旋转角度
     * @param formatName 目标图片格式
     */
    public static void markWebImageByIcon(String iconPath, String srcImgPath, String targetPath, Integer degree, String formatName) {
        OutputStream os = null;
        try {
            Image srcImg = ImageIO.read(WatermarkUtil.getImageStream(srcImgPath));
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            int srcWidth = srcImg.getWidth(null);
            int srcHeight = srcImg.getHeight(null);
            // 1、得到画笔对象
            Graphics2D g = buffImg.createGraphics();

            // 2、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

            // 3、设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
            }

            // 4、水印图片的路径 水印图片一般为gif或者png的,这样可设置透明度
            ImageIcon imgIcon = new ImageIcon(iconPath);
            // 5、得到Image对象。
            Image img = imgIcon.getImage();
            int iconWidth = img.getWidth(null);
            int iconHeight = img.getHeight(null);
            if (iconWidth < 0 || iconHeight < 0) {
                System.out.println("无法获取到水印图片,请确认 " + iconPath + " 路径是否存在水印图片!!");
            }
            double dmarkWidth = srcWidth * 0.8;// 设置水印的宽度为图片宽度的0.4倍
            double dmarkHeight = dmarkWidth * ((double) iconWidth / (double) iconHeight);//强转为double计算宽高比例

            int imarkWidth = (int) dmarkWidth;
            int imarkHeight = (int) dmarkHeight;

            // 6、水印图片的位置
            int x = (srcWidth - imarkWidth) / 2;
            int y = (srcHeight - imarkHeight) / 2;

            g.drawImage(img, x, y, imarkWidth, imarkHeight, null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            // 7、释放资源
            g.dispose();
            // 8、生成图片
            os = new FileOutputStream(targetPath);
            ImageIO.write(buffImg, formatName, os);
            System.out.println("[添加水印]图片完成添加水印图片");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("[添加水印] Exception, message=" + e.getMessage());
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * @param logoText   水印文字
     * @param srcImgPath 网络图片url
     * @param targetPath 目标图片路径
     * @param degree     水印文字旋转角度
     * @param color      水印文字颜色
     * @param formatName 文件后缀格式
     */
    public static void markWebImageByText(String logoText, String srcImgPath, String targetPath, Integer degree, Color color, String formatName) {
        InputStream is = null;
        OutputStream os = null;
        try {
            // 1、源图片
            Image srcImg = ImageIO.read(WatermarkUtil.getImageStream(srcImgPath));
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
            // 4、设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree), buffImg.getWidth() / 4, buffImg.getHeight() / 4);
            }
            // 5、设置水印文字颜色
            g.setColor(color);
            // 6、设置水印文字Font
            g.setFont(new Font("宋体", Font.BOLD, buffImg.getHeight() / 6));
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
            // 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
//            g.drawString(logoText,  buffImg.getWidth()/2 , buffImg.getHeight()/2);
            g.drawString(logoText, buffImg.getWidth() / 4, buffImg.getHeight() / 4);
            // 9、释放资源
            g.dispose();
            // 10、生成图片
            os = new FileOutputStream(targetPath);
            ImageIO.write(buffImg, formatName, os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is)
                    is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 
     * @param logoText   水印文字
     * @param srcImgPath 网络图片url
     * @param targetPath 目标图片路径
     * @param color      水印文字颜色
     * @param formatName 文件后缀格式
     */
    public static void markWebImageByText(String logoText, String srcImgPath, String targetPath, Color color, String formatName) {
        InputStream is = null;
        OutputStream os = null;
        try {
            // 1、源图片:通过url获取网络文件流
            Image srcImg = ImageIO.read(WatermarkUtil.getImageStream(srcImgPath));
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

            // 5、设置水印文字颜色
            g.setColor(color);
            // 6、设置水印文字Font
            g.setFont(new Font("宋体", Font.BOLD, buffImg.getHeight() / 6));
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
            // 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
//            g.drawString(logoText,  buffImg.getWidth()/2 , buffImg.getHeight()/2);
            g.drawString(logoText, buffImg.getWidth() / 4, buffImg.getHeight() / 4);
            // 9、释放资源
            g.dispose();
            // 10、生成图片
            os = new FileOutputStream(targetPath);


            ImageIO.write(buffImg, formatName, os);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取网络图片流
     *
     * @param url
     * @return
     */
    private static InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常,图片路径为:" + url);
            e.printStackTrace();
        }
        return null;
    }





    //TODO:*************************************************************** 本地图片 *********************************************************
    /**
     * 给图片添加图片水印、可设置水印图片旋转角度
     *
     * @param iconPath   水印图片路径
     * @param srcImage   源图片文件流
     * @param targetPath 目标图片路径
     * @param degree     水印图片旋转角度
     * @param formatName 目标图片格式
     */
    public static boolean markImageByIcon(String iconPath, InputStream srcImage, String targetPath, Integer degree, String formatName) {

        if (StringUtils.isBlank(iconPath) || StringUtils.isBlank(targetPath) || StringUtils.isBlank(formatName)) {
            return false;
        }
        OutputStream os = null;
        try {

            Image srcImg = ImageIO.read(srcImage);
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            int srcWidth = srcImg.getWidth(null);
            int srcHeight = srcImg.getHeight(null);
            // 1、得到画笔对象
            Graphics2D g = buffImg.createGraphics();

            // 2、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

            // 3、设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
            }

            // 4、水印图片的路径 水印图片一般为gif或者png的,这样可设置透明度
            ImageIcon imgIcon = new ImageIcon(iconPath);
            // 5、得到Image对象。
            Image img = imgIcon.getImage();
            int iconWidth = img.getWidth(null);
            int iconHeight = img.getHeight(null);
            double dmarkWidth = srcWidth * 0.9;// 设置水印的宽度为图片宽度的0.9倍
            double dmarkHeight = dmarkWidth * ((double) iconWidth / (double) iconHeight);//强转为double计算宽高比例

            int imarkWidth = (int) dmarkWidth;
            int imarkHeight = (int) dmarkHeight;

            // 6、水印图片的位置
            int x = (srcWidth - imarkWidth) / 2;
            int y = (srcHeight - imarkHeight) / 2;

            g.drawImage(img, x, y, imarkWidth, imarkHeight, null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            // 7、释放资源
            g.dispose();
            // 8、生成图片
            os = new FileOutputStream(targetPath);
            ImageIO.write(buffImg, formatName, os);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }



    public static void main(String[] args) {
        String fileType = "jpg";
        String absolutePath = "D://test/01.jpg";
        String iconPath = "D://test/icon.png";
        String targetPath = "D://test/";
        // 文字水印
        WatermarkUtil.markImageByText("文字水印", absolutePath, targetPath + "textwater.jpg", Color.BLUE, fileType);
        // 图片水印
        WatermarkUtil.markImageByIcon(iconPath, absolutePath, targetPath + "iconwater.jpg", null, fileType);


        String url = "http://10.0.0.0:8080/image/202106011442318460.jpg";
        // 文字水印
        WatermarkUtil.markWebImageByText("文字水印", url, targetPath + "textwater2.jpg", Color.BLUE, fileType);
        // 图片水印
        WatermarkUtil.markWebImageByIcon(iconPath, url, targetPath + "iconwater2.jpg", null, fileType);

    }

}



在这里插入图片描述

参考:
java 根据网络图片url获取InputStream

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值