最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java用自帶的Image IO給圖片添加水印

 更新時(shí)間:2021年06月15日 15:36:15   作者:廢物大師兄  
本文主要介紹了如何采用Java自帶的Image IO實(shí)現(xiàn)圖片添加水印的需求,并整合了一些其他功能,感興趣的朋友可以參考下

1.  文字水印

import sun.font.FontDesignMetrics;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * @Author ChengJianSheng
 * @Date 2021/6/10
 */
public class WatermarkUtil
{
    public static void main(String[] args) throws IOException
        {
            addText("F:/1.jpeg", "我的夢(mèng)想是成為火影");
        }
        /**
         * 加文字水印
         * @param srcPath   原文件路徑
         * @param content   文字內(nèi)容
         * @throws IOException
         */
    public static void addText(String srcPath, String content) throws IOException
    {
        //  讀取原圖片信息
        BufferedImage srcImage = ImageIO.read(new File(srcPath));
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        //  創(chuàng)建畫筆,設(shè)置繪圖區(qū)域
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufferedImage.createGraphics();
        g.drawImage(srcImage, 0, 0, width, height, null);
        //        g.drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        g.setFont(new Font("宋體", Font.PLAIN, 32));
        g.setColor(Color.RED);
        //  計(jì)算文字長(zhǎng)度
        int len = g.getFontMetrics(g.getFont()).charsWidth(content.toCharArray(), 0, content.length());
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(g.getFont());
        int len2 = metrics.stringWidth(content);
        System.out.println(len);
        System.out.println(len2);
        //  計(jì)算文字坐標(biāo)
        int x = width - len - 10;
        int y = height - 20;
        //        int x = width - 2 * len;
        //        int y = height - 1 * len;
        g.drawString(content, x, y);
        g.dispose();
        //  輸出文件
        FileOutputStream fos = new FileOutputStream("F:/2.png");
        ImageIO.write(bufferedImage, "png", fos);
        fos.flush();
        fos.close();
    }
}

可以設(shè)置文字透明度

 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.8f)); 

2.  旋轉(zhuǎn)文字

import sun.font.FontDesignMetrics;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * @Author ChengJianSheng
 * @Date 2021/6/10
 */
public class WatermarkUtil
{
    // 水印透明度
    private static final float alpha = 0.5 f;
    // 水印文字字體
    private static final Font font = new Font("宋體", Font.BOLD, 30);
    // 水印文字顏色
    private static final Color color = Color.RED;
    public static void main(String[] args) throws IOException
        {
            addText("F:/1.jpeg", "圖片由木葉村提供,僅供忍者聯(lián)軍使用!");
        }
        /**
         * 加文字水印
         * @param srcPath   原文件路徑
         * @param content   文字內(nèi)容
         * @throws IOException
         */
    public static void addText(String srcPath, String content) throws IOException
    {
        //  讀取原圖片信息
        BufferedImage srcImage = ImageIO.read(new File(srcPath));
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        //  創(chuàng)建畫筆,設(shè)置繪圖區(qū)域
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufferedImage.createGraphics();
        g.drawImage(srcImage, 0, 0, width, height, null);
        //        g.drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        //  旋轉(zhuǎn)文字
        AffineTransform affineTransform = g.getTransform();
        affineTransform.rotate(Math.toRadians(-30), 0, 0);
        Font rotatedFont = font.deriveFont(affineTransform);
        g.setFont(rotatedFont); // 字體
        g.setColor(color); // 顏色
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); // 透明度
        //  計(jì)算文字長(zhǎng)度
        int len = g.getFontMetrics(g.getFont()).charsWidth(content.toCharArray(), 0, content.length());
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(g.getFont());
        int len2 = metrics.stringWidth(content);
        System.out.println(len);
        System.out.println(len2);
        //  計(jì)算水印文字坐標(biāo)
        int x = width / 5;
        int y = height / 3 * 2;
        g.drawString(content, x, y);
        g.dispose();
        //  輸出文件
        FileOutputStream fos = new FileOutputStream("F:/2.png");
        ImageIO.write(bufferedImage, "png", fos);
        fos.flush();
        fos.close();
    }
}

畫矩形框

import sun.font.FontDesignMetrics;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * @Author ChengJianSheng
 * @Date 2021/6/10
 */
public class WatermarkUtil
{
    // 水印透明度
    private static final float alpha = 0.5 f;
    // 水印文字字體
    private static final Font font = new Font("宋體", Font.BOLD, 30);
    // 水印文字顏色
    private static final Color color = Color.RED;
    public static void main(String[] args) throws IOException
        {
            addText("F:/1.jpeg", "圖片由木葉村提供,僅供忍者聯(lián)軍使用!");
        }
        /**
         * 加文字水印
         * @param srcPath   原文件路徑
         * @param content   文字內(nèi)容
         * @throws IOException
         */
    public static void addText(String srcPath, String content) throws IOException
    {
        //  讀取原圖片信息
        BufferedImage srcImage = ImageIO.read(new File(srcPath));
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        //  創(chuàng)建畫筆,設(shè)置繪圖區(qū)域
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufferedImage.createGraphics();
        g.drawImage(srcImage, 0, 0, width, height, null);
        g.setFont(font); // 字體
        g.setColor(color); // 顏色
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); // 透明度
        //  計(jì)算文字寬高度
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
        int textWidth = metrics.stringWidth(content); //  文字寬度
        int textHeight = metrics.getHeight(); //  文字高度
        //  計(jì)算文字坐標(biāo)
        int x = (width - textWidth) / 2;
        int y = (height + textHeight) / 2;
        //  寫文字
        g.drawString(content, x, y);
        //  畫矩形
        int padding = 10; // 內(nèi)邊距
        g.drawRect(x - padding / 2, y - textHeight, textWidth + padding, textHeight + padding);
        g.dispose();
        //  輸出文件
        FileOutputStream fos = new FileOutputStream("F:/2.png");
        ImageIO.write(bufferedImage, "png", fos);
        fos.flush();
        fos.close();
    }
}

3.  旋轉(zhuǎn)坐標(biāo)軸

import sun.font.FontDesignMetrics;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * @Author ChengJianSheng
 * @Date 2021/6/10
 */
public class WatermarkUtil
{
    // 水印透明度
    private static final float alpha = 0.5 f;
    // 水印文字字體
    private static final Font font = new Font("宋體", Font.BOLD, 30);
    // 水印文字顏色
    private static final Color color = Color.RED;
    public static void main(String[] args) throws IOException
        {
            addText("F:/1.jpeg", "圖片由木葉村提供,僅供忍者聯(lián)軍使用!");
        }
        /**
         * 加文字水印
         * @param srcPath   原文件路徑
         * @param content   文字內(nèi)容
         * @throws IOException
         */
    public static void addText(String srcPath, String content) throws IOException
    {
        //  讀取原圖片信息
        BufferedImage srcImage = ImageIO.read(new File(srcPath));
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        //  創(chuàng)建畫筆,設(shè)置繪圖區(qū)域
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufferedImage.createGraphics();
        g.drawImage(srcImage, 0, 0, width, height, null);
        g.setFont(font); // 字體
        g.setColor(color); // 顏色
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); // 透明度
        //  計(jì)算文字寬高度
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
        int textWidth = metrics.stringWidth(content); //  文字寬度
        int textHeight = metrics.getHeight(); //  文字高度
        //  旋轉(zhuǎn)坐標(biāo)軸
        g.translate(-width / 5, height / 4);
        g.rotate(-30 * Math.PI / 180);
        //  計(jì)算文字坐標(biāo)
        int x = (width - textWidth) / 2;
        int y = (height + textHeight) / 2;
        //  寫文字
        g.drawString(content, x, y);
        //  畫矩形
        int padding = 10; // 內(nèi)邊距
        g.drawRect(x - padding / 2, y - textHeight, textWidth + padding, textHeight + padding);
        g.dispose();
        //  輸出文件
        FileOutputStream fos = new FileOutputStream("F:/2.png");
        ImageIO.write(bufferedImage, "png", fos);
        fos.flush();
        fos.close();
    }
}

結(jié)合下載功能,完整的代碼如下:

/**
 * 下載
 */
@
GetMapping("/download")
public void download(@RequestParam("mediaId") String mediaId, HttpServletRequest request, HttpServletResponse response) throws IOException
{
    SysFile sysFile = sysFileService.getByMediaId(mediaId);
    if(null == sysFile)
    {
        throw new IllegalArgumentException("文件不存在");
    }
    String mimeType = request.getServletContext().getMimeType(sysFile.getPath());
    System.out.println(mimeType);
    response.setContentType(sysFile.getContentType());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(sysFile.getOriginalFilename(), "UTF-8"));
    //        FileInputStream fis = new FileInputStream(sysFile.getPath());
    ServletOutputStream sos = response.getOutputStream();
    WatermarkUtil.addText(sysFile.getPath(), "哈哈哈哈", sos);
    //        IOUtils.copy(fis, sos);
    //        IOUtils.closeQuietly(fis);
    IOUtils.closeQuietly(sos);
}
import sun.font.FontDesignMetrics;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
/**
 * @Author ChengJianSheng
 * @Date 2021/6/10
 */
public class WatermarkUtil
{
    // 水印透明度
    private static final float alpha = 0.5 f;
    // 水印文字字體
    private static final Font font = new Font("宋體", Font.BOLD, 30);
    // 水印文字顏色
    private static final Color color = Color.RED;
    /**
     * 加文字水印
     * @param srcPath   原文件路徑
     * @param content   文字內(nèi)容
     * @throws IOException
     */
    public static void addText(String srcPath, String content, OutputStream outputStream) throws IOException
    {
        //  讀取原圖片信息
        BufferedImage srcImage = ImageIO.read(new File(srcPath));
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        //  畫板
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //  畫筆
        Graphics2D g = bufferedImage.createGraphics();
        g.drawImage(srcImage, 0, 0, width, height, null);
        g.setFont(font); // 字體
        g.setColor(color); // 顏色
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); // 透明度
        //  計(jì)算文字寬高度
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
        int textWidth = metrics.stringWidth(content); //  文字寬度
        int textHeight = metrics.getHeight(); //  文字高度
        //  旋轉(zhuǎn)坐標(biāo)軸
        g.translate(-width / 5, height / 4);
        g.rotate(-30 * Math.PI / 180);
        //  計(jì)算文字坐標(biāo)
        int x = (width - textWidth) / 2;
        int y = (height + textHeight) / 2;
        //  寫文字
        g.drawString(content, x, y);
        //  畫矩形
        int padding = 10; // 內(nèi)邊距
        g.drawRect(x - padding / 2, y - textHeight, textWidth + padding, textHeight + padding);
        g.dispose();
        //  輸出
        ImageIO.write(bufferedImage, "png", outputStream);
    }
}

另外的寫法

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

/**
 * @ProjectName: test
 * @Package: com.test.utils
 * @ClassName: MyTest
 * @Author: luqiming
 * @Description:
 * @Date: 2020/10/29 11:48
 * @Version: 1.0
 */
public class AddWatermarkUtil {
    public static void waterPress(String srcImgPath, String outImgPath,
                           Color markContentColor, int fontSize, String waterMarkContent) {
        try {
            String[] waterMarkContents = waterMarkContent.split("\\|\\|");
            // 讀取原圖片信息
            File srcImgFile = new File(srcImgPath);
            Image srcImg = ImageIO.read(srcImgFile);
            int srcImgWidth = srcImg.getWidth(null);
            int srcImgHeight = srcImg.getHeight(null);
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            // 得到畫筆對(duì)象
            Graphics2D g = bufImg.createGraphics();
            // 設(shè)置起點(diǎn)
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            Font font = new Font("宋體", Font.PLAIN, fontSize);
            // 根據(jù)圖片的背景設(shè)置水印顏色
            g.setColor(markContentColor);
            // 設(shè)置水印文字字體
            g.setFont(font);
            // 數(shù)組長(zhǎng)度
            int contentLength = waterMarkContents.length;
            // 獲取水印文字中最長(zhǎng)的
            int maxLength = 0;
            for (int i = 0; i < contentLength; i++) {
                int fontlen = getWatermarkLength(waterMarkContents[i], g);
                if (maxLength < fontlen) {
                    maxLength = fontlen;
                }
            }

            for (int j = 0; j < contentLength; j++) {
                waterMarkContent = waterMarkContents[j];
                int tempX = 10;
                int tempY = fontSize;
                // 單字符長(zhǎng)度
                int tempCharLen = 0;
                // 單行字符總長(zhǎng)度臨時(shí)計(jì)算
                int tempLineLen = 0;
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < waterMarkContent.length(); i++) {
                    char tempChar = waterMarkContent.charAt(i);
                    tempCharLen = getCharLen(tempChar, g);
                    tempLineLen += tempCharLen;
                    if (tempLineLen >= srcImgWidth) {
                        // 長(zhǎng)度已經(jīng)滿一行,進(jìn)行文字疊加
                        g.drawString(sb.toString(), tempX, tempY);
                        // 清空內(nèi)容,重新追加
                        sb.delete(0, sb.length());
                        tempLineLen = 0;
                    }
                    // 追加字符
                    sb.append(tempChar);
                }
                // 通過設(shè)置后兩個(gè)輸入?yún)?shù)給水印定位
                g.drawString(sb.toString(), 20, srcImgHeight - (contentLength - j - 1) * tempY-50);
            }
            g.dispose();

            // 輸出圖片
            FileOutputStream outImgStream = new FileOutputStream(outImgPath);
            ImageIO.write(bufImg, "jpg", outImgStream);
            outImgStream.flush();
            outImgStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int getCharLen(char c, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charWidth(c);
    }

    /**
     * 獲取水印文字總長(zhǎng)度
     *
     * @paramwaterMarkContent水印的文字
     * @paramg
     * @return水印文字總長(zhǎng)度
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(
                waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }


    public static void main(String[] args) {
        // 原圖位置, 輸出圖片位置, 水印文字顏色, 水印文字
        String font = "張?zhí)鞇踻|就很完美||2020-05-27 17:00:00";
        String inputAddress = "F:/UpupooWallpaper/1.jpg";
        String outputAddress = "F:/UpupooWallpaper/1.jpg";
        Color color = Color.GREEN;
        waterPress(inputAddress, outputAddress, color, 50, font);
    }
}

添加效果

關(guān)于水印位置,需要修改:

//左下角
 g.drawString(sb.toString(), 0, srcImgHeight - (contentLength - j - 1) * tempY);

//右下角
 g.drawString(sb.toString(), srcImgWidth - maxLength, srcImgHeight - (contentLength - j - 1) * tempY);

以上就是Java用自帶的Image IO給圖片添加水印的詳細(xì)內(nèi)容,更多關(guān)于Java 圖片添加水印的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 深入剖析構(gòu)建JSON字符串的三種方式(推薦)

    深入剖析構(gòu)建JSON字符串的三種方式(推薦)

    下面小編就為大家?guī)硪黄钊肫饰鰳?gòu)建JSON字符串的三種方式(推薦)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-10-10
  • java開啟遠(yuǎn)程debug竟有兩種參數(shù)(最新推薦)

    java開啟遠(yuǎn)程debug竟有兩種參數(shù)(最新推薦)

    這篇文章主要介紹了java開啟遠(yuǎn)程debug竟有兩種參數(shù),本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-07-07
  • MyEclipse配置JDK的全過程

    MyEclipse配置JDK的全過程

    這篇文章主要介紹了MyEclipse配置JDK的全過程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-04-04
  • SpringBoot中注解實(shí)現(xiàn)定時(shí)任務(wù)的兩種方式

    SpringBoot中注解實(shí)現(xiàn)定時(shí)任務(wù)的兩種方式

    這篇文章主要介紹了SpringBoot中注解實(shí)現(xiàn)定時(shí)任務(wù)的兩種方式,SpringBoot 定時(shí)任務(wù)是一種在SpringBoot應(yīng)用中自動(dòng)執(zhí)行任務(wù)的機(jī)制,通過使用Spring框架提供的@Scheduled注解,我們可以輕松地創(chuàng)建定時(shí)任務(wù),需要的朋友可以參考下
    2023-10-10
  • java file.renameTo返回false的原因及解決方案

    java file.renameTo返回false的原因及解決方案

    這篇文章主要介紹了java file.renameTo返回false的原因及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • 詳解如何為SpringBoot Web應(yīng)用的日志方便追蹤

    詳解如何為SpringBoot Web應(yīng)用的日志方便追蹤

    在Web應(yīng)用程序領(lǐng)域,有效的請(qǐng)求監(jiān)控和可追溯性對(duì)于維護(hù)系統(tǒng)完整性和診斷問題至關(guān)重要,SpringBoot是一種用于構(gòu)建Java應(yīng)用程序的流行框架,在本文中,我們探討了在SpringBoot中向日志添加唯一ID的重要性,需要的朋友可以參考下
    2023-11-11
  • Java?ConcurrentHashMap實(shí)現(xiàn)線程安全的代碼示例

    Java?ConcurrentHashMap實(shí)現(xiàn)線程安全的代碼示例

    眾所周知ConcurrentHashMap是HashMap的多線程版本,HashMap?在并發(fā)操作時(shí)會(huì)有各種問題,而這些問題,只要使用ConcurrentHashMap就可以完美解決了,本文將給詳細(xì)介紹ConcurrentHashMap是如何保證線程安全的
    2023-05-05
  • Java中List的使用方法簡(jiǎn)單介紹

    Java中List的使用方法簡(jiǎn)單介紹

    這篇文章主要針對(duì)Java中List的使用方法為大家介紹了進(jìn)行簡(jiǎn)單介紹,List是個(gè)集合接口,只要是集合類接口都會(huì)有個(gè)“迭代子”( Iterator ),利用這個(gè)迭代子,就可以對(duì)list內(nèi)存的一組對(duì)象進(jìn)行操作,感興趣的小伙伴們可以參考一下
    2016-07-07
  • springboot操作ldap全過程

    springboot操作ldap全過程

    這篇文章主要介紹了springboot操作ldap全過程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • 沒有編輯器的環(huán)境下是如何創(chuàng)建Servlet(Tomcat+Java)項(xiàng)目的?

    沒有編輯器的環(huán)境下是如何創(chuàng)建Servlet(Tomcat+Java)項(xiàng)目的?

    今天給大家?guī)淼氖顷P(guān)于Java的相關(guān)知識(shí),文章圍繞著在沒有編輯器的環(huán)境下如何創(chuàng)建Servlet(Tomcat+Java)項(xiàng)目展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06

最新評(píng)論

庐江县| 永年县| 湖州市| 东乡县| 温泉县| 孝感市| 体育| 清原| 莒南县| 泗洪县| 徐闻县| 辽宁省| 乌兰浩特市| 珠海市| 稻城县| 图木舒克市| 漠河县| 六盘水市| 庆安县| 湘潭市| 文登市| 汝州市| 望奎县| 延津县| 庆阳市| 吉水县| 辽阳市| 延津县| 图们市| 明星| 荆州市| 阜城县| 兴宁市| 柯坪县| 平江县| 斗六市| 永和县| 凤城市| 宁津县| 静宁县| 台东市|