用javax给图片加水印和文字

package com.duolun.school.ddjd.utils;

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.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.function.Consumer;

/**
 * 给图片加水印或加文字
 *
 * @Author zhangchen
 * @Date 2022/7/25
 **/
public class PictureFile {
    /**
     * 根据路径读取文件
     *
     * @param srcImgPath
     * @return
     * @throws IOException
     */
    public static Image readImageByPath(String srcImgPath) throws IOException {
        return ImageIO.read(new File(srcImgPath));
    }

    /**
     * 创建BufferedImage缓存
     *
     * @param srcImg
     * @return
     * @throws IOException
     */
    public static BufferedImage creatBufferedImage(Image srcImg) throws IOException {
        return new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
    }

    /**
     * 创建水印的集合
     *
     * @param g    Graphics2D画笔
     * @param list 水印的集合
     * @throws IOException
     */
    public static void createIconImage(Graphics2D g, List<Icon> list) throws IOException {
        ImageIcon imgIcon = null;
        Image img = null;
        int width = 0;
        int height = 0;
        for (Icon icon : list) {
            // 水印图象的路径 水印一般为gif或者png的,这样可设置透明度
            imgIcon = new ImageIcon(icon.iconPath);
            width = (int) (imgIcon.getIconWidth() * icon.ratio);
            height = (int) (imgIcon.getIconHeight() * icon.ratio);
            //可以设置水印的长宽
            imgIcon.setImage(imgIcon.getImage().getScaledInstance(width, height, Image.SCALE_DEFAULT));
            // 得到Image对象。
            img = imgIcon.getImage();
            // 透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, icon.alpha));
            // 表示水印图片的位置
            g.drawImage(img, icon.absoluteX, icon.absoluteY, null);
        }
    }

    /**
     * 创建画笔
     *
     * @param buffImg BufferedImage图像缓冲的对象,所有的修改先是对缓冲区进行修改,最后刷新到原图
     * @param srcImg  图片的地址
     * @return
     */
    public static Graphics2D createGraphics2D(BufferedImage buffImg, Image srcImg) {
        // 得到画笔对象
        Graphics2D g = buffImg.createGraphics();
        // 设置对线段的锯齿状边缘处理
        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);
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        return g;
    }

    /**
     * 创建字体格式
     *
     * @param g    画笔
     * @param list 文本信息列表
     */
    public static void createFont(Graphics2D g, List<Text> list) {
        Font font = null;
        for (Text text : list) {
            g.setColor(text.color);
            font = new Font(text.fontStyle, Font.PLAIN, text.fontSize);
            g.setFont(font);
            g.drawString(text.content, text.absoluteX, text.absoluteY);
        }
    }


    /**
     * 图片生成水印的框架
     *
     * @param srcImgPath 处理图片的地址
     * @param targerPath 处理完输出的地址
     * @param consumer   消费者,留给别的函数填充是加水印还是字体
     */
    public static void markImage(String srcImgPath, String targerPath, Consumer<Graphics2D> consumer) {
        OutputStream os = null;
        try {
            Image srcImg = readImageByPath(srcImgPath);
            BufferedImage buffImg = creatBufferedImage(srcImg);
            Graphics2D g = createGraphics2D(buffImg, srcImg);
            consumer.accept(g);
            g.dispose();
            os = new FileOutputStream(targerPath);
            // 生成图片
            ImageIO.write(buffImg, "jpg", os);
            System.out.println("图片加工完成。。。。。。");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给图片加水印
     *
     * @param srcImgPath
     * @param targerPath
     * @param icon
     */
    public static void markImageByIcon(String srcImgPath, String targerPath, List<Icon> icon) {
        markImage(srcImgPath, targerPath, (g) -> {
            try {
                createIconImage(g, icon);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 给图片加文字
     *
     * @param srcImgPath
     * @param targerPath
     * @param text
     */
    public static void markImageByText(String srcImgPath, String targerPath, List<Text> text) {
        markImage(srcImgPath, targerPath, (g) -> {
            createFont(g, text);
        });
    }

    /**
     * 给图片加水印和文字
     *
     * @param srcImgPath
     * @param targerPath
     * @param icon
     * @param text
     */
    public static void markImageByIconAndFont(String srcImgPath, String targerPath, List<Icon> icon, List<Text> text) {
        markImage(srcImgPath, targerPath, (g) -> {
            try {
                createIconImage(g, icon);
            } catch (IOException e) {
                e.printStackTrace();
            }
            createFont(g, text);
        });
    }

    /**
     * 水印配置类
     **/
    public static class Icon {
        private int absoluteX;
        private int absoluteY;
        private String iconPath;
        private float ratio;
        private float alpha;

        /**
         * @param absoluteX x轴坐标
         * @param absoluteY y轴坐标
         * @param iconPath  水印的地址
         * @param ratio     水印缩放的比例  0f-1f
         * @param alpha     清晰度         0-1
         */
        public Icon(int absoluteX, int absoluteY, String iconPath, float ratio, float alpha) {
            this.absoluteX = absoluteX;
            this.absoluteY = absoluteY;
            this.iconPath = iconPath;
            this.ratio = ratio;
            this.alpha = alpha;
        }
    }

    /**
     * 信息配置类
     **/
    public static class Text {
        private String content;
        private float absoluteX;
        private float absoluteY;
        private int fontSize;
        private String fontStyle = "宋体";
        private Color color = Color.black;

        /**
         * @param content   字符串内容
         * @param absoluteX x轴坐标
         * @param absoluteY y轴坐标
         * @param fontSize  字体大小
         * @param fontStyle 字体的形式
         * @param color     字体的颜色
         */
        public Text(String content, float absoluteX, float absoluteY, int fontSize, String fontStyle, Color color) {
            this.content = content;
            this.absoluteX = absoluteX;
            this.absoluteY = absoluteY;
            this.fontSize = fontSize;
            this.fontStyle = fontStyle;
            this.color = color;
        }

        public Text(String content, float absoluteX, float absoluteY, int fontSize) {
            this.content = content;
            this.absoluteX = absoluteX;
            this.absoluteY = absoluteY;
            this.fontSize = fontSize;
        }
    }

    public static void main(String[] args) {
        String srcImgPath = "src/main/resources/1.jpg";
        String iconPath = "src/main/resources/jx.png";
        String targerPath = "src/main/resources/合并后.jpg";
        List<Icon> list = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        list.add(new Icon(1350, 620, iconPath, 0.4f, 1));
        list.add(new Icon(1350, 450, iconPath, 0.4f, 1));
        List<Text> text = new ArrayList<>();
        text.add(new Text("张三", 279, 209, 26));
        text.add(new Text("男", 562, 212, 26));
        text.add(new Text("321283199909121234", 810, 210, 26));
        text.add(new Text(dateFormat.format(calendar.getTime()), 1220, 210, 26));
        // 给图片添加图片水印
        PictureFile.markImageByIconAndFont(srcImgPath, targerPath, list, text);
//        PictureFile.markImageByIcon(srcImgPath, targerPath,list);
//        PictureFile.markImageByText(srcImgPath, targerPath,text);

    }
}

效果图就不懒得写了,自己改路径和x,y的坐标即可 


版权声明:本文为m0_52739267原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。