1.编写工具类
- package com.test;
-
- import javax.imageio.ImageIO;
- import java.awt.*;
- import java.awt.image.BufferedImage;
- import java.io.File;
- import java.io.IOException;
-
-
- public class WatermarkUtil {
-
-
-
- public static void addTextWatermark(File srcFile, String text, Font font, Color color) throws IOException {
-
- Image image = ImageIO.read(srcFile);
-
-
- int width = image.getWidth(null), height = image.getHeight(null);
-
-
- BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
-
-
- Graphics2D g = bufferedImage.createGraphics();
-
-
- g.drawImage(image, 0, 0, width, height, null);
-
-
- g.setFont(font);
- g.setColor(color);
-
- g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
-
-
-
-
- int h = height-font.getSize(), w = width-text.length()*font.getSize()-10;
-
-
- g.drawString(text, w, h);
-
-
- g.dispose();
-
- String fileFullName = srcFile.getName();
- int splitIndex = fileFullName.lastIndexOf(".");
- String fileName = fileFullName.substring(0, splitIndex);
- String extName = fileFullName.substring(splitIndex + 1);
-
-
- ImageIO.write(bufferedImage, extName, new File("D:\\test\\"+fileName+"_watermark."+extName));
-
- }
- }
-
-
2.测试
- public static void main(String[] args) throws IOException{
- File file = new File("D:\\test\\src.jpg");
- WatermarkUtil.addTextWatermark(file, "我是水印", new Font("黑体", 0, 20), new Color(248,0,0));
- }
-
-
3.添加效果