Java用自带的Image IO给图片添加水印

 更新时间:2021年06月15日 15:36:15   作者:废物大师兄  
本文主要介绍了如何采用Java自带的Image IO实现图片添加水印的需求,并整合了一些其他功能,感兴趣的朋友可以参考下

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", "我的梦想是成为火影");
        }
        /**
         * 加文字水印
         * @param srcPath   原文件路径
         * @param content   文字内容
         * @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();
        //  创建画笔,设置绘图区域
        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);
        //  计算文字长度
        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);
        //  计算文字坐标
        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();
    }
}

可以设置文字透明度

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

2.  旋转文字

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", "图片由木叶村提供,仅供忍者联军使用!");
        }
        /**
         * 加文字水印
         * @param srcPath   原文件路径
         * @param content   文字内容
         * @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();
        //  创建画笔,设置绘图区域
        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);
        //  旋转文字
        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)); // 透明度
        //  计算文字长度
        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);
        //  计算水印文字坐标
        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", "图片由木叶村提供,仅供忍者联军使用!");
        }
        /**
         * 加文字水印
         * @param srcPath   原文件路径
         * @param content   文字内容
         * @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();
        //  创建画笔,设置绘图区域
        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)); // 透明度
        //  计算文字宽高度
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
        int textWidth = metrics.stringWidth(content); //  文字宽度
        int textHeight = metrics.getHeight(); //  文字高度
        //  计算文字坐标
        int x = (width - textWidth) / 2;
        int y = (height + textHeight) / 2;
        //  写文字
        g.drawString(content, x, y);
        //  画矩形
        int padding = 10; // 内边距
        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.  旋转坐标轴

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", "图片由木叶村提供,仅供忍者联军使用!");
        }
        /**
         * 加文字水印
         * @param srcPath   原文件路径
         * @param content   文字内容
         * @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();
        //  创建画笔,设置绘图区域
        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)); // 透明度
        //  计算文字宽高度
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
        int textWidth = metrics.stringWidth(content); //  文字宽度
        int textHeight = metrics.getHeight(); //  文字高度
        //  旋转坐标轴
        g.translate(-width / 5, height / 4);
        g.rotate(-30 * Math.PI / 180);
        //  计算文字坐标
        int x = (width - textWidth) / 2;
        int y = (height + textHeight) / 2;
        //  写文字
        g.drawString(content, x, y);
        //  画矩形
        int padding = 10; // 内边距
        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();
    }
}

结合下载功能,完整的代码如下:

/**
 * 下载
 */
@
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   文字内容
     * @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)); // 透明度
        //  计算文字宽高度
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
        int textWidth = metrics.stringWidth(content); //  文字宽度
        int textHeight = metrics.getHeight(); //  文字高度
        //  旋转坐标轴
        g.translate(-width / 5, height / 4);
        g.rotate(-30 * Math.PI / 180);
        //  计算文字坐标
        int x = (width - textWidth) / 2;
        int y = (height + textHeight) / 2;
        //  写文字
        g.drawString(content, x, y);
        //  画矩形
        int padding = 10; // 内边距
        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);
            // 得到画笔对象
            Graphics2D g = bufImg.createGraphics();
            // 设置起点
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            Font font = new Font("宋体", Font.PLAIN, fontSize);
            // 根据图片的背景设置水印颜色
            g.setColor(markContentColor);
            // 设置水印文字字体
            g.setFont(font);
            // 数组长度
            int contentLength = waterMarkContents.length;
            // 获取水印文字中最长的
            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;
                // 单字符长度
                int tempCharLen = 0;
                // 单行字符总长度临时计算
                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) {
                        // 长度已经满一行,进行文字叠加
                        g.drawString(sb.toString(), tempX, tempY);
                        // 清空内容,重新追加
                        sb.delete(0, sb.length());
                        tempLineLen = 0;
                    }
                    // 追加字符
                    sb.append(tempChar);
                }
                // 通过设置后两个输入参数给水印定位
                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);
    }

    /**
     * 获取水印文字总长度
     *
     * @paramwaterMarkContent水印的文字
     * @paramg
     * @return水印文字总长度
     */
    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 = "张天爱||就很完美||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);
    }
}

添加效果

关于水印位置,需要修改:

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

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

以上就是Java用自带的Image IO给图片添加水印的详细内容,更多关于Java 图片添加水印的资料请关注脚本之家其它相关文章!

相关文章

  • 深入剖析构建JSON字符串的三种方式(推荐)

    深入剖析构建JSON字符串的三种方式(推荐)

    下面小编就为大家带来一篇深入剖析构建JSON字符串的三种方式(推荐)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • java开启远程debug竟有两种参数(最新推荐)

    java开启远程debug竟有两种参数(最新推荐)

    这篇文章主要介绍了java开启远程debug竟有两种参数,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-07-07
  • MyEclipse配置JDK的全过程

    MyEclipse配置JDK的全过程

    这篇文章主要介绍了MyEclipse配置JDK的全过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-04-04
  • SpringBoot中注解实现定时任务的两种方式

    SpringBoot中注解实现定时任务的两种方式

    这篇文章主要介绍了SpringBoot中注解实现定时任务的两种方式,SpringBoot 定时任务是一种在SpringBoot应用中自动执行任务的机制,通过使用Spring框架提供的@Scheduled注解,我们可以轻松地创建定时任务,需要的朋友可以参考下
    2023-10-10
  • java file.renameTo返回false的原因及解决方案

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

    这篇文章主要介绍了java file.renameTo返回false的原因及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • 详解如何为SpringBoot Web应用的日志方便追踪

    详解如何为SpringBoot Web应用的日志方便追踪

    在Web应用程序领域,有效的请求监控和可追溯性对于维护系统完整性和诊断问题至关重要,SpringBoot是一种用于构建Java应用程序的流行框架,在本文中,我们探讨了在SpringBoot中向日志添加唯一ID的重要性,需要的朋友可以参考下
    2023-11-11
  • Java ConcurrentHashMap实现线程安全的代码示例

    Java ConcurrentHashMap实现线程安全的代码示例

    众所周知ConcurrentHashMap是HashMap的多线程版本,HashMap 在并发操作时会有各种问题,而这些问题,只要使用ConcurrentHashMap就可以完美解决了,本文将给详细介绍ConcurrentHashMap是如何保证线程安全的
    2023-05-05
  • Java中List的使用方法简单介绍

    Java中List的使用方法简单介绍

    这篇文章主要针对Java中List的使用方法为大家介绍了进行简单介绍,List是个集合接口,只要是集合类接口都会有个“迭代子”( Iterator ),利用这个迭代子,就可以对list内存的一组对象进行操作,感兴趣的小伙伴们可以参考一下
    2016-07-07
  • springboot操作ldap全过程

    springboot操作ldap全过程

    这篇文章主要介绍了springboot操作ldap全过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-05-05
  • 没有编辑器的环境下是如何创建Servlet(Tomcat+Java)项目的?

    没有编辑器的环境下是如何创建Servlet(Tomcat+Java)项目的?

    今天给大家带来的是关于Java的相关知识,文章围绕着在没有编辑器的环境下如何创建Servlet(Tomcat+Java)项目展开,文中有非常详细的介绍及代码示例,需要的朋友可以参考下
    2021-06-06

最新评论