图片加水印:
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.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageAddWatermarkUtil {
public static void imageAddWatermark(String srcFileUrl) {
File srcFolder = new File(srcFileUrl);
// int i = 0;
for (File file : srcFolder.listFiles()) {
// File srcImgFile = new File(srcFileUrl);//得到文件
if (file.isFile() && file.getName().endsWith(".jpg")) {
Image srcImg = null;
try {
srcImg = ImageIO.read(file);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // 文件转化为图片
int srcImgWidth = srcImg.getWidth(null);// 获取图片的宽
int srcImgHeight = srcImg.getHeight(null);// 获取图片的高
// 加水印
Font font = new Font("微软雅黑", Font.PLAIN, 10);
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2d = bufImg.createGraphics();
graphics2d.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
graphics2d.setColor(Color.WHITE); // 设置水印颜色
graphics2d.setFont(font); // 设置字体
// 设置水印的坐标
String name = file.getName();
String waterMarkContent = name.substring(0, name.indexOf("."));
// System.out.println(getWatermarkLength(waterMarkContent, graphics2d));
int x = srcImgWidth - getWatermarkLength(waterMarkContent, graphics2d) - 3;
int y = srcImgHeight - 3;
graphics2d.drawString(waterMarkContent, x, y); // 画出水印
graphics2d.dispose();
// 输出图片
FileOutputStream outImgStream = null;
try {
outImgStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ImageIO.write(bufImg, "jpg", outImgStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
outImgStream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
outImgStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
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) {
}
}