欢迎光临
一个有态度、有温度的分享型博客

Java实现给图片加水印的两种方式

我博客中的图片发现经常被别的网站盗用,而且不注明出处,因此不得不加上水印,Java代码添加水印的方式具体如下。

代码示例:

package xyz.rxblog;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author https://www.cobcmw.com
 */
public class WaterMarkExample {

    public static void main(String[] args) {
        File[] imageFiles = new WaterMarkExample().listAllFiles("D:\\cobcmw");
        if (imageFiles != null && imageFiles.length > 0) {
            for (File imageFile : imageFiles) {
                String imageFormat = new WaterMarkExample().getFileExtension(imageFile.getAbsoluteFile());
                //new WaterMarkExample().addTextWaterMark(imageFile, imageFile, "来源:https://www.cobcmw.com", 45, imageFormat);
                new WaterMarkExample().addImageWaterMark(imageFile, "D:\\watermark.png", imageFile.getAbsolutePath(), 45, imageFormat);
            }
        }
    }

    /**
     * @param originImagePath 文件完整路径+文件名
     * @param imageOutPath
     * @param markText
     * @param degree
     * @param imageFormat     输出的图片格式
     */
    public void addTextWaterMark(File originImagePath, File imageOutPath, String markText, Integer degree, String imageFormat) {
        // 主图片的路径
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            Image originImage = ImageIO.read(originImagePath);
            BufferedImage buffImg = new BufferedImage(originImage.getWidth(null), originImage.getHeight(null), BufferedImage.TYPE_INT_RGB);

            // 得到画笔对象!
            Graphics2D g = buffImg.createGraphics();

            // 设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

            g.drawImage(originImage.getScaledInstance(originImage.getWidth(null), originImage.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

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

            // 设置颜色
            g.setColor(Color.red);
            // 设置 Font
            g.setFont(new Font("宋体", Font.BOLD, 30));
            float alpha = 0.5f;
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

            // 第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y) .
            g.drawString(markText, 0, buffImg.getHeight() / 2);

            g.dispose();

            outputStream = new FileOutputStream(imageOutPath);

            // 输出添加水印之后的图片
            ImageIO.write(buffImg, imageFormat, outputStream);

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

    public void addImageWaterMark(File originImagePath, String markImagePath, String imageOutPath, Integer degree, String imageFormat) {
        OutputStream outputStream = null;
        try {
            Image originImage = ImageIO.read(originImagePath);

            BufferedImage buffImg = new BufferedImage(originImage.getWidth(null), originImage.getHeight(null), BufferedImage.TYPE_INT_RGB);

            // 得到画笔对象
            Graphics2D g = buffImg.createGraphics();

            // 设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

            g.drawImage(originImage.getScaledInstance(originImage.getWidth(null), originImage.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

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

            // 水印图象的路径 水印一般为gif或者png的,这样可设置透明度
            ImageIcon imgIcon = new ImageIcon(markImagePath);

            // 得到Image对象。
            Image img = imgIcon.getImage();

            float alpha = 0.5f; // 透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

            // 表示水印图片的位置
            g.drawImage(img, 20, buffImg.getHeight() / 2, null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            g.dispose();
            outputStream = new FileOutputStream(imageOutPath);

            // 生成图片
            ImageIO.write(buffImg, imageFormat, outputStream);

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

    /**
     * 列出目录下所有的文件&文件夹
     *
     * @param dirName 路径名称
     * @return
     * @author www.cobcmw.com
     */
    public File[] listAllFiles(String dirName) {
        //如果dir不以文件分隔符结尾,自动添加文件分隔符
        if (!dirName.endsWith(File.separator)) {
            dirName = dirName + File.separator;
        }
        File dirFile = new File(dirName);
        //如果dir对应的文件不存在,或者不是一个文件夹则退出
        if (!dirFile.exists() || (!dirFile.isDirectory())) {
            System.out.println("List失败!找不到目录:" + dirName);
        }

        //列出文件夹下所有的文件
        File[] files = dirFile.listFiles();
        return files;
    }


    /**
     * 获取文件后缀的方法
     *
     * @param file 要获取文件后缀的文件
     * @return 文件后缀
     * @author www.cobcmw.com
     */
    public String getFileExtension(File file) {
        String extension = "";
        try {
            if (file != null && file.exists()) {
                String name = file.getName();
                extension = name.substring(name.lastIndexOf(".") + 1);
            }
        } catch (Exception e) {
            extension = "";
        }
        return extension;
    }
}

参考文章:

  1. Java实现给图片添加水印
  2. 图片添加水印(Java 实现)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址