1. 程式人生 > 其它 >java 圖片新增水印(文字水印+圖片水印)

java 圖片新增水印(文字水印+圖片水印)

技術標籤:javajava

一、圖片水印(水印檔案覆蓋到原始檔上)

/**
     * @param buffImg 原始檔(BufferedImage)
     * @param waterImg 水印檔案(BufferedImage)
     * @param x       X偏移量
     * @param y       Y偏移量
     * @param alpha   透明度, 選擇值從0.0~1.0: 完全透明~完全不透明
     * @return BufferedImage
     * @throws IOException
     * @Title: 構造圖片
     * @Description: 生成水印並返回java.awt.image.BufferedImage
     */
    public static BufferedImage overlyingImage(BufferedImage buffImg, BufferedImage waterImg, int x, int y, float alpha) throws IOException {
        // 建立Graphics2D物件,用在底圖物件上繪圖
        Graphics2D g2d = buffImg.createGraphics();
        int waterImgWidth = waterImg.getWidth();// 獲取層圖的寬度
        int waterImgHeight = waterImg.getHeight();// 獲取層圖的高度
        // 在圖形和影象中實現混合和透明效果
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
        // 繪製
        g2d.drawImage(waterImg, x, y, waterImgWidth, waterImgHeight, null);
        g2d.dispose();// 釋放圖形上下文使用的系統資源
        return buffImg;
    }

效果圖:

原始檔(buffImg):
水印檔案(waterImg):
最後效果:

根據需要設定透明度、旋轉角度、鋪滿樣式

二、文字水印(由於要設定旋轉效果,所以為了讓展示效果鋪滿整個圖片,所以x和y的偏移量取負數,效果好看些)

/** 文字水印
     * @param buffImg 原始檔(BufferedImage)
     * @param x       X偏移量
     * @param y       Y偏移量
     * @param alpha   透明度, 選擇值從0.0~1.0: 完全透明~完全不透明
     * @return BufferedImage
     * @throws IOException
     * @Title: 構造圖片
     * @Description: 生成水印並返回java.awt.image.BufferedImage
     */
    public static BufferedImage overlyingImageFont(BufferedImage buffImg, int x, int y, float alpha) throws IOException {
        // 建立Graphics2D物件,用在底圖物件上繪圖
        Graphics2D g = buffImg.createGraphics();
        // 3、設定對線段的鋸齒狀邊緣處理
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        //設定旋轉(旋轉角度,旋轉x軸定點,y軸定點)
        g.rotate(Math.toRadians(45),
                0D,
                0D);
        Font font = new Font("宋體", Font.BOLD, 20);
        //設定字型
        g.setFont(font);
        //設定顏色
        g.setColor(Color.GRAY);
        // 設定透明效果
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
        // 8、第一引數->設定的內容,後面兩個引數->文字在圖片上的座標位置(x,y)
        /**開始平鋪介面*/
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                y+=150;
                g.drawString("我是文字內容", x, y);
            }
            x+=150;
            y=0;
        }
        g.dispose();// 釋放圖形上下文使用的系統資源

        return buffImg;
    }

效果圖:

原始檔(buffImg):
最後效果: