@Slf4j public class ImageUtils { @Test public void test1() throws IOException { //得到全部的圖片文件 Path path = Paths.get("D:\\Files\\CDN\\file\\_resources"); ...
@Slf4j
public class ImageUtils {
@Test
public void test1() throws IOException {
//得到全部的圖片文件
Path path = Paths.get("D:\\Files\\CDN\\file\\_resources");
if (!Files.exists(path)) {
throw new RuntimeException("目錄或文件不存在!");
}
List<Path> collect = new ArrayList<>();
if (Files.isDirectory(path)) {
collect = Files.walk(path).filter(temp -> temp.getFileName().toString().endsWith(".png")).collect(Collectors.toList());
} else {
boolean b = path.getFileName().toString().endsWith(".png");
if (b) {
collect.add(path);
}
}
if (CollectionUtils.isEmpty(collect)) {
return;
}
for (Path temp : collect) {
changeImg(temp.toFile());
}
}
/**
* 加水印
*
* @param srcImgFile 本地圖片地址
* @throws IOException
*/
private void changeImg(File srcImgFile) throws IOException {
//將文件對象轉化為圖片對象
Image srcImg = ImageIO.read(srcImgFile);
//獲取圖片的寬
int srcImgWidth = srcImg.getWidth(null);
//獲取圖片的高
int srcImgHeight = srcImg.getHeight(null);
// System.out.println("圖片的寬:" + srcImgWidth);
// System.out.println("圖片的高:" + srcImgHeight);
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
// 加水印
//創建畫筆
Graphics2D g = bufImg.createGraphics();
//繪製原始圖片
g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
//-------------------------文字水印 start----------------------------
//根據圖片的背景設置水印顏色
g.setColor(new Color(158,160,161));
//設置字體 畫筆字體樣式為微軟雅黑,加粗,文字大小為12pt
g.setFont(new Font("微軟雅黑", Font.BOLD, 12));
//水印內容
String waterMarkContent = "https://www.cnblogs.com/lemonpuer";
//設置水印的坐標
int x = (srcImgWidth - getWatermarkLength(waterMarkContent, g)) - 5;
int y = srcImgHeight - 5;
//畫出水印 第一個參數是水印內容,第二個參數是x軸坐標,第三個參數是y軸坐標
g.drawString(waterMarkContent, x, y);
g.dispose();
//-------------------------文字水印 end----------------------------
//待存儲的地址
// String tarImgPath = "F:\\0a8de9fc675db86eab79aa36b7575374.png";
// 輸出圖片
FileOutputStream outImgStream = new FileOutputStream(srcImgFile);
ImageIO.write(bufImg, "png", outImgStream);
log.info("圖片{}成功添加水印",srcImgFile.getName());
outImgStream.flush();
outImgStream.close();
}
/**
* 獲取水印文字的長度
*
* @param waterMarkContent
* @param g
* @return
*/
private int getWatermarkLength(String waterMarkContent, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
}
}