package 水印;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
/**
-
给图片添加水印
-
@author tgy
/
public class img水印 {
/*- @param args
*/
public static void main(String[] args) throws Exception {
File file = new File(“C:\Users\86151\Desktop\123.jpg”);
InputStream inputStream = new FileInputStream(file);
img水印.watermarkImg(inputStream, “C:\Users\86151\Desktop”, “图片名称”, “jpg”, Color.red, “水印”, -45);
}
/**
-
给图片添加单个文字水印、可设置水印文字旋转角度
-
@param file 需要添加水印的图片路径
-
@param output 添加水印后图片输出路径
-
@param imageName 图片名称(如:11111)
-
@param imageType 图片类型(如:jpg)
-
@param color 水印文字的颜色
-
@param word 水印文字
-
@param degree 水印文字旋转角度,为null表示不旋转
org.apache.pdfbox pdfbox 2.0.12 org.apache.poi poi-ooxml 3.13 org.mortbay.jetty servlet-api 2.5-20081211 e-iceblue spire.doc.free 2.7.3 org.apache.poi poi 4.0.0 org.apache.poi poi-ooxml 4.0.0
*/
public static void watermarkImg(InputStream file, String output, String imageName, String imageType, Color color, String word, Integer degree) {
try {
//读取原图片信息
Image img = ImageIO.read(file);
int width = img.getWidth(null);
int height = img.getHeight(null);
//加水印
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.drawImage(img, 0, 0, width, height, null);
//设置水印字体样式
Font font = new Font(“宋体”, Font.PLAIN, 30);
//根据图片的背景设置水印颜色
g.setColor(color);
if (null != degree) {
//设置水印旋转
g.rotate(Math.toRadians(degree), (double) bi.getWidth() / 2, (double) bi.getHeight() / 2);
}
g.setFont(font);
int x = width / 3;
int y = height / 2;
//水印位置
g.drawString(word, x, y);
g.dispose();
//输出图片
File sf = new File(output, imageName + “.” + imageType);
ImageIO.write(bi, imageType, sf); // 保存图片
} catch (Exception e) {
e.printStackTrace();
}
}
}
- @param args