【java 图片增加水印】

图片增加水印

工具类

package com.ruoyi.bnbackstage.util;

import com.ruoyi.bnbackstage.domain.ShuiYinClass;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import javax.imageio.ImageIO;

//图片打文字工具类
@Service
public class MarkImageUtils {

    /**
     * 单行文字打印
     * @param filePath 原图片
     * @param outFile  输出图片
     * @param text     水印文字
     * @param color    颜色
     * @param font     字体
     * @param x        水印起始X坐标
     * @param y        水印起始Y坐标
     * @return 添加水印是否成功 true-成功 false-失败
     */
    public  boolean waterMark(String filePath, String outFile,
                                    String text, Color color, Font font, int x, int y) {
        String result = "打水印失败!";
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
            BufferedImage im = ImageIO.read(fis);//读取原图片
            int width = im.getWidth();//原图片宽
            int height = im.getHeight();//原图片高
            //判断水印起始x和y坐标是否小于原图片宽和高
            if (x > width || y > height) {
                System.out.println(result);
                return false;
            }
            Graphics g = im.getGraphics();//创建画板
            g.setColor(color);//设置颜色
            g.setFont(font);//设置文字样式
            g.drawString(text, x, y);//向画板上写字
            g.dispose();//释放资源
            ImageIO.write(im, "png", new File(outFile));
        } catch (IOException e) {
            System.out.println(result);
            return false;
        } finally {
            closeFileInputStream(fis);
        }
        result = "打水印成功!";
        System.out.println(result);
        return true;
    }


    //多行文本打水印数据
    public  boolean waterMarkMany(String filePath, String outFile,
                                        List<ShuiYinClass> suiyinList, Color color, Font font, int x, int y) {
        String result = "打水印失败!";
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
            BufferedImage im = ImageIO.read(fis);//读取原图片
            int width = im.getWidth();//原图片宽
            int height = im.getHeight();//原图片高
            //判断水印起始x和y坐标是否小于原图片宽和高
            if (x > width || y > height) {
                System.out.println(result);
                return false;
            }
            Graphics g = im.getGraphics();//创建画板
            g.setColor(color);//设置颜色
            g.setFont(font);//设置文字样式

            //向画板上写字
            for (int i = 0; i <suiyinList.size() ; i++) {
                y += 35;
                g.drawString(suiyinList.get(i).getShuiYinText(),x, y);
            }

            g.dispose();//释放资源

            //判断打印水印的文件类型 是jpg还是png
            if (filePath.contains(".jpg")){
                ImageIO.write(im, "jpg", new File(outFile));
            }else {
                ImageIO.write(im, "png", new File(outFile));
            }

        } catch (IOException e) {
            System.out.println(result);
            return false;
        } finally {
            closeFileInputStream(fis);
        }
        result = "打水印成功!";
        System.out.println(result);
        return true;
    }

    /**
     * 关闭文件输入流
     * @param fis
     */
    public  void closeFileInputStream (FileInputStream fis){
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 通过文件路径获取尺寸
     * @param filePath
     * @return
     * @throws IOException
     */
    public Map getPhotoSize(String filePath) throws IOException {
        Map map = new HashMap();
        File picture = new File(filePath);
        BufferedImage sourceImg =ImageIO.read(new FileInputStream(picture));
        map.put("width", sourceImg.getWidth());
        map.put("height", sourceImg.getHeight());
        return map;
    }

}

调用方式

String timePath = timeUtil.getTimeYMDone();//通过时间做唯一标识
        String fileName = file.getOriginalFilename();//获取文件名
        String savePathOld =   "D:/downloadZip" + "/" + "one" + timePath + fileName;//传入的文件
        String savePathNew =   "D:/downloadZip" + "/" + "two" + timePath + fileName;//新生成的文件
        File dest = new File(savePathOld);
        file.transferTo(dest); // 保存文件

		//处理传入文件参数 打印水印的参数
        List<ShuiYinClass> list = new ArrayList<>();

		//计算图片高度和宽度 文字水印印在图片指定位置
        Map fileSizeMap = markImageUtils.getPhotoSize(savePathOld);
        System.out.println("图片宽度:" +fileSizeMap.get("width"));
        System.out.println("图片高度:"+fileSizeMap.get("height"));
        Integer width = Integer.valueOf(fileSizeMap.get("width").toString());//图片宽度
        Integer height = Integer.valueOf(fileSizeMap.get("height").toString());//图片高度
        int startWidth = width - 330;//宽度减50得到右侧靠边宽度
        int statrHeight = height - 250;//高度暂时减300测试
        Color color=new Color(	255,0,0);//设置字体颜色
        Font font = new Font("微软雅黑", Font.BOLD, 20);//设置字体字号

        //图片增加水印
        boolean addTestResult = markImageUtils.waterMarkMany(savePathOld, savePathNew, list, color, font, startWidth, statrHeight);
        if (addTestResult == true){

            /*通过本地文件 转为MultipartFile后上传至oss 返回路径给前端*/
            File uploadOssFile = new File(savePathNew);
            FileInputStream fileInputStream = null;
            fileInputStream = new FileInputStream(uploadOssFile);
            //增加水印后的 图片文件流 可调用oss上传方式 传到指定图片存储位置
            MultipartFile multipartFile = new MockMultipartFile(uploadOssFile.getName(), uploadOssFile.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
		}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值