java springboot实现图片添加文字/图片水印(单个/多个)

一.Controller

 @PostMapping(value = {"/watermark"},
            produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public String watermark(@RequestParam("file") MultipartFile image) throws Exception {
//        MarkService markService = new TextMarkServiceImpl();  //单个文字水印
//        MarkService markService = new MoreTextServiceImpl();  //多个文字水印
//        MarkService markService = new ImgMarkServiceImpl();   //单个图片水印
        MarkService markService = new MoreImgMarkServiceImpl(); //多个图片水印
        //将上传的图片上传到项目中类路径下面
        String path = "";
        String realUploadPath = InvestInvitationInfoController.class.getClassLoader().getResource(path).getPath();
        String imageURL =uploadImage( image, path, realUploadPath );
        File imgFile=new File(realUploadPath + image.getOriginalFilename());
        //添加水印
        String watermark = markService.watermark(imgFile, image.getOriginalFilename(), path, realUploadPath);
        return watermark;
    }
    //将上传的图片上传到项目中类路径下面
	public String uploadImage(MultipartFile file, String uploadPath, String physicalUploadPath ) {

        String filePath = physicalUploadPath + file.getOriginalFilename();

        try {
            File targetFile=new File(filePath);
            FileUtils.writeByteArrayToFile(targetFile, file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return uploadPath + "/" + file.getOriginalFilename();
    }

二.Service

import java.awt.*;
import java.io.File;

public interface MarkService {
    public static final String MARK_TEXT="LMS";  //字体水印
    public static final String FONT_NAME="微软雅黑";
    public static final int FONT_STYLE= Font.BOLD;
    public static final int FONT_SIZE=20;
    public static final Color FONT_COLOR=Color.BLACK;
    public static final  int X=10;
    public static final int Y=10;
    public static final float ALPHA=0.3f;  //透明度
    public static final String LOGO="mimi.jpg";  //图片水印,提前保存在类路径下的图片
    public String watermark(File img, String imgName, String imgpath, String realImgPath);
}

三.ServiceImpl
(一)单个文字水印

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


public class MarkServiceImpl implements MarkService {
    public static final String MARK_TEXT = "LMS";
    public static final String FONT_NAME = "微软雅黑";
    public static final int FONT_STYLE = Font.BOLD;
    public static final int FONT_SIZE = 120;
    public static final Color FONT_COLOR = Color.BLACK;
    public static final int X = 10;
    public static final int Y = 10;
    public static final float ALPHA = 0.3f;
    public static final String LOGO = "logo.png";

    @Override
    public String watermark(File img, String imgFileName, String imgpath, String realImgPath) {

        //创建图像编码工具
        FileOutputStream os = null;
        String logoFileName = "logo_" + imgFileName;
        try {
            //获取原图大小
            Image image = ImageIO.read(img);
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = bufferedImage.createGraphics();
            graphics.drawImage(image, 0, 0, width, height, null);
            //设置文件水印
            graphics.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));
            graphics.setColor(FONT_COLOR);

            //获取文本水印的真正高度与宽度
            int wid = FONT_SIZE * getLength(MARK_TEXT);
            int hei = FONT_SIZE;

            int widDiff = width - wid;
            int heiDiff = height - hei;
            int x = X;
            int y = Y;
            if (x > widDiff) x = widDiff;
            if (y > heiDiff) x = widDiff;

            //设置透明度
            graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
            graphics.drawString(MARK_TEXT, x, y + FONT_SIZE);
            graphics.dispose();

            os = new FileOutputStream(realImgPath + "/" + logoFileName);
            JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return imgpath + "/" + logoFileName;
    }

    //计算文本长度
    public int getLength(String text) {
        int length = text.length();
        for (int i = 0; i < 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;
    }
  }

(二)单个图片水印

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

public class ImgMarkServiceImpl implements MarkService {
    @Override
    public String watermark(File img, String imgFileName, String imgpath, String realImgPath) {
        //创建图像编码工具
        FileOutputStream os = null;
        String logoFileName = "logo_" + imgFileName;
        String logoPath=realImgPath+"/"+LOGO;
        try {
            //获取原图大小
            Image image = ImageIO.read(img);
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = bufferedImage.createGraphics();
            graphics.drawImage(image, 0, 0, width, height, null);

            File logo = new File(logoPath);
            Image imageLogo = ImageIO.read(logo);
            int logoWidth = imageLogo.getWidth(null);
            int logoHeight = imageLogo.getHeight(null);

            int widDiff = width - logoWidth;
            int heiDiff = height - logoHeight;
            int x = X;
            int y = Y;
            if (x > widDiff) x = widDiff;
            if (y > heiDiff) x = widDiff;

            //设置透明度
            graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
            graphics.drawImage(imageLogo,x,y,null);
            graphics.dispose();

            os = new FileOutputStream(realImgPath + "/" + logoFileName);
            ImageIO.write(bufferedImage, "jpg", os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return imgpath + "/" + logoFileName;
    }
   }

(三)多个文字水印

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

public class MoreTextServiceImpl implements MarkService {
    @Override
    public String watermark(File img, String imgFileName, String imgpath, String realImgPath) {
        //创建图像编码工具
        FileOutputStream os = null;
        String logoFileName = "logo_" + imgFileName;
        try {
            //获取原图大小
            Image image = ImageIO.read(img);
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = bufferedImage.createGraphics();
            graphics.drawImage(image, 0, 0, width, height, null);

            //设置文字水印
            graphics.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));
            graphics.setColor(FONT_COLOR);

            //获取文本水印的真正高度与宽度
            int wid = FONT_SIZE * getLength(MARK_TEXT);
            int hei = FONT_SIZE;

            //设置透明度
            graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
            //旋转图片
            graphics.rotate(Math.toRadians(30), bufferedImage.getWidth() / 2, bufferedImage.getHeight() / 2);
            int x = -width / 2;
            int y = -height / 2;
            while (x < width * 1.5) {
                y = -height / 2;
                while (y < height * 1.5) {
                    graphics.drawString(MARK_TEXT, x, y);
                    y += hei + y;
                }
                x += wid + x;
            }
            graphics.dispose();

            os = new FileOutputStream(realImgPath + "/" + logoFileName);
//            JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
            ImageIO.write(bufferedImage, "jpg", os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return imgpath + "/" + logoFileName;
    }

    //计算文本长度
    public int getLength(String text) {
        int length = text.length();
        for (int i = 0; i < 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;
    }
}

(四)多个图片水印

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

public class MoreImgMarkServiceImpl implements MarkService {
    @Override
    public String watermark(File img, String imgFileName, String imgpath, String realImgPath) {
        //创建图像编码工具
        FileOutputStream os = null;
        String logoFileName = "logo_" + imgFileName;
        String logoPath=realImgPath+"/"+LOGO;
        try {
            //获取原图大小
            Image image = ImageIO.read(img);
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = bufferedImage.createGraphics();
            graphics.drawImage(image, 0, 0, width, height, null);

            //获取图片水印
            File logo = new File(logoPath);
            Image imageLogo = ImageIO.read(logo);
            int logoWidth = imageLogo.getWidth(null);
            int logoHeight = imageLogo.getHeight(null);

            //设置透明度
            graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
            //旋转图片
            graphics.rotate(Math.toRadians(30), bufferedImage.getWidth() / 2, bufferedImage.getHeight() / 2);
            int x = -width / 2;
            int y = -height / 2;
            //循环添加水印
            while (x < width * 1.5) {
                y = -height / 2;
                while (y < height * 1.5) {
                    graphics.drawImage(imageLogo,x,y,null);
                    y += logoHeight + y;
                }
                x += logoWidth + x;
            }

            graphics.dispose();

            os = new FileOutputStream(realImgPath + "/" + logoFileName);
//            JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
            ImageIO.write(bufferedImage, "jpg", os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return imgpath + "/" + logoFileName;
    }
  }

你可能感兴趣的:(java springboot实现图片添加文字/图片水印(单个/多个))