/**
* 图片添加水印效果
* @param filename 图片文件名称
* @param resultFilename 目标文件名称
* @throws IOException
*/
public void watermarkForImage(String filename,String resultFilename) throws IOException{
//创建文件对象
File file = new File(filename);
//判断文件是否存在
if (!file.exists()) {
System.out.println("文件不存在");
return;
}
ImageIcon imageIcon = new ImageIcon(file.getPath());
BufferedImage bufferedImage = new BufferedImage(
imageIcon.getIconWidth(), imageIcon.getIconHeight(), BufferedImage.TYPE_INT_BGR);
Graphics2D graphics2d = (Graphics2D)bufferedImage.getGraphics();
graphics2d.drawImage(imageIcon.getImage(), 0, 0, null);
AlphaComposite alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER,1f);
graphics2d.setComposite(alphaComposite);
//设置颜色
graphics2d.setColor(Color.WHITE);
graphics2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//字体设置
graphics2d.setFont(new Font("微软雅黑", Font.BOLD, 32));
//水印文字
String watermarkText = "水印效果测试";
//设置水印文字和文字
graphics2d.drawString(watermarkText, 0, 32);
graphics2d.dispose();
File resultFile = new File(resultFilename);
ImageIO.write(bufferedImage, "png", resultFile);
System.out.println("success!");
}
Java实现图片水印效果
最新推荐文章于 2024-09-06 19:01:55 发布