溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java怎么實現(xiàn)添加文字水印和圖片水印功能

發(fā)布時間:2023-05-04 11:06:49 來源:億速云 閱讀:132 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“Java怎么實現(xiàn)添加文字水印和圖片水印功能”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“Java怎么實現(xiàn)添加文字水印和圖片水印功能”吧!

    添加水印

    為圖片添加水印的主要作用是保護圖片版權(quán),防止圖片被未經(jīng)授權(quán)的人使用或傳播。為圖片添加水印是一種常用的圖片處理技術(shù)。在Java 中可以使用JDK自帶的 Graphics2D 類來繪制水印。可以添加圖片水印或者文字水印。

    Java 2D API是Java 平臺上用于繪制 2D 圖形的一組類和方法。它支持多種格式的圖像、字體和顏色管理,并提供了許多高級特性,如 alpha 融合、深度緩沖區(qū)等。

    Java 2D API介紹

    1.創(chuàng)建一個繪制圖形的對象

    使用Graphics2D 類來創(chuàng)建一個繪制圖形的對象。Graphics2D 對象是擴展了 Graphics 類的一個子類,提供了更多的繪制功能。

    // 創(chuàng)建一個大小為 800x600 像素的空白圖像
    BufferedImage image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
    // 遞給 Graphics2D 對象以進行繪制操作
    Graphics2D g2d = image.createGraphics();

    2.繪制基本圖形

    Java 2D API 支持繪制各種基本的 2D 圖形,例如線段、矩形、橢圓、弧形等

    // 繪制一條線段
    g2d.drawLine(100, 100, 200, 200);
    // 繪制一個矩形
    g2d.drawRect(300, 100, 100, 50);
    // 繪制一個橢圓
    g2d.drawOval(500, 100, 100, 150);
    // 繪制一個弧形
    g2d.drawArc(100, 300, 100, 100, 0, 90);

    3.繪制文本

    可以使用 Graphics2D 對象的 drawString() 方法來在圖像上繪制字符串文本

    // 將字符串 "Hello, Java 2D!" 繪制在坐標(biāo) (200, 400) 處
    g2d.drawString("Hello, Java 2D!", 200, 400);

    4.繪制圖像

    支持加載和繪制各種格式的圖像,例如 JPEG、PNG、GIF 等。還可以使用 ImageIO 類加載圖像文件,并使用 Graphics2D 對象的 drawImage() 方法將其繪制到圖像上。

    // 從指定的文件路徑加載一張圖片,并將其繪制在圖像的左上角
    BufferedImage image = ImageIO.read(new File("image.jpg"));
    g2d.drawImage(image, 0, 0, null);

    5.設(shè)置繪制屬性

    可以使用 Graphics2D 對象的 set 方法來設(shè)置多種繪制屬性,例如顏色、字體、線寬等。

    // 設(shè)置繪制顏色為紅色
    g2d.setColor(Color.RED);
    // 設(shè)置字體為 Arial,大小為 24
    g2d.setFont(new Font("Arial", Font.PLAIN, 24));
    // 設(shè)置線寬為 3 像素
    g2d.setStroke(new BasicStroke(3));

    繪制文字水印

    對圖片添加文字水印,執(zhí)行步驟操作如下:

    • 使用ImageIO類加載需要添加水印的圖片

    • 創(chuàng)建一個BufferedImage的自定義圖像對象,并使用Graphics2D對象將原始圖像繪制到該對象上

    • 創(chuàng)建字體對象,并設(shè)置字體、顏色、透明度等屬性

    • 使用Graphics2D對象的drawString()方法在需要添加水印的位置繪制字符串

    • 使用ImageIO類將修改后的圖像保存到指定目錄

        public static void addWatermark(File input, File out, String text, int fontSize) {
            // 讀取原圖片
            BufferedImage image = null;
            try {
                image = ImageIO.read(input);
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 獲取圖片的寬度和高度
            int width = image.getWidth();
            int height = image.getHeight();
            // 創(chuàng)建一個圖片緩存對象
            BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            // 獲取圖片的畫筆
            Graphics2D g = newImage.createGraphics();
            // 將原圖片繪制到緩存圖片上
            g.drawImage(image, 0, 0, width, height, null);
            // 創(chuàng)建字體對象
            Font font = new Font("微軟雅黑", Font.BOLD, fontSize);
            // 創(chuàng)建字體渲染上下文
            FontRenderContext frc = new FontRenderContext(null, true, true);
            // 計算字符串的寬度和高度
            Rectangle2D bounds = font.getStringBounds(text, frc);
            // 字符寬度
            int strWidth = (int) bounds.getWidth();
            // 字符高度
            int strHeight = (int) bounds.getHeight();
            // 設(shè)置水印的字體樣式
            g.setFont(font);
            // 設(shè)置水印的顏色
            g.setColor(Color.red);
            // 設(shè)置水印的位置 根據(jù)需要再自行調(diào)整寬度、高度
            g.drawString(text, width - strWidth - 10, height - strHeight + 15);
            // 釋放圖形上下文使用的系統(tǒng)資源
            g.dispose();
            // 保存帶水印的圖片
            try {
                ImageIO.write(newImage, "png", out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public static void main(String[] args) {
            File input = new File("D://test.png");
            File out = new File("D://watermark.png");
            // 水印文本內(nèi)容,中文轉(zhuǎn)Unicode
            String text = "\u6dfb\u52a0\u6c34\u5370";
            addWatermark(input, out, text, 20);
        }

    繪制圖片水印

    對圖片添加圖片水印,執(zhí)行步驟操作如下:

    • 使用ImageIO類加載需要添加水印的圖片

    • 創(chuàng)建一個BufferedImage的自定義圖像對象,并使用Graphics2D對象將原始圖像繪制到該對象上

    • 使用ImageIO類加載水印圖片,并設(shè)置透明度等屬性

    • 繪制水印圖片,釋放相關(guān)資源

    • 使用ImageIO類將修改后的圖像保存到指定目錄

        public static void addWatermark(File input, File out, File watermarkImage) {
            // 讀取添加水印的圖片
            BufferedImage image = null;
            try {
                image = ImageIO.read(input);
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 獲取圖片的寬度和高度
            int width = image.getWidth();
            int height = image.getHeight();
            // 創(chuàng)建一個圖片緩存對象
            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(watermarkImage);
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 獲取水印圖片的寬度和高度
            int wmWidth = watermark.getWidth();
            int wmHeight = watermark.getHeight();
            // 設(shè)置水印圖片的透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
            // 繪制水印圖片
            g.drawImage(watermark, width - wmWidth - 10, height - wmHeight - 10, wmWidth, wmHeight, null);
            // 釋放圖形上下文使用的系統(tǒng)資源
            g.dispose();
            // 保存帶水印的圖片
            try {
                ImageIO.write(newImage, "png", out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public static void main(String[] args) {
            File input = new File("D://test.png");
            File out = new File("D://watermark.png");
            File watermarkImage = new File("D://watermarkImage .png");
            addWatermark(input, out, watermarkImage);
        }

    循環(huán)添加文字水印

    public class AddWatermarkUtils {
        // 水印字體
        private static final Font FONT = new Font("微軟雅黑", Font.PLAIN, 24);
        // 透明度
        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 markWithContent(String inputImgPath, Font font, Color markContentColor,
                                           String waterMarkContent,
                                           String outImgPath) throws IOException {
            // 讀取原圖片信息
            File srcFile = new File(inputImgPath);
            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);
            // 創(chuàng)建繪圖工具
            Graphics2D graphics = bufImg.createGraphics();
            // 畫入原始圖像
            graphics.drawImage(srcImg, 0, 0, imgWidth, imgHeight, null);
            // 設(shè)置水印顏色
            graphics.setColor(markContentColor);
            // 設(shè)置水印透明度
            graphics.setComposite(COMPOSITE);
            // 設(shè)置傾斜角度
            graphics.rotate(Math.toRadians(-35), (double) bufImg.getWidth() / 2,
                    (double) bufImg.getHeight() / 2);
            // 設(shè)置水印字體
            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();
            // 循環(huán)添加水印
            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();
            try (FileOutputStream fos = new FileOutputStream(outFile)) {
                // 輸出圖片
                ImageIO.write(bufImg, "jpg", fos);
                fos.flush();
            }
        }
        /**
         * 計算水印文本長度
         * 中文長度即文本長度
         * 英文長度為文本長度二分之一
         */
        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;
        }
    }
        public static void main(String[] args) throws IOException {
            // 輸入圖片路徑
            String inputFile = "D://test.png";
            // 輸出圖片路徑
            String outputFile = "D://watermark.png";
            // 水印文本內(nèi)容,中文轉(zhuǎn)Unicode
            String watermarkText = "\u6dfb\u52a0\u6c34\u5370";
            AddWatermarkUtils.markWithContent(inputFile, FONT, Color.darkGray, watermarkText, outputFile);
        }

    到此,相信大家對“Java怎么實現(xiàn)添加文字水印和圖片水印功能”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI