1. import java.awt.AlphaComposite;
  2. import java.awt.Graphics2D;
  3. import java.awt.image.BufferedImage;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import javax.imageio.ImageIO;
  7. public class NewImageUtils {
  8. /**
  9. *
  10. * @Title: 构造图片
  11. * @Description: 生成水印并返回java.awt.image.BufferedImage
  12. * @param file
  13. * 源文件(图片)
  14. * @param waterFile
  15. * 水印文件(图片)
  16. * @param x
  17. * 距离右下角的X偏移量
  18. * @param y
  19. * 距离右下角的Y偏移量
  20. * @param alpha
  21. * 透明度, 选择值从0.0~1.0: 完全透明~完全不透明
  22. * @return BufferedImage
  23. * @throws IOException
  24. */
  25. public static BufferedImage watermark(File file, File waterFile, int x, int y, float alpha) throws IOException {
  26. // 获取底图
  27. BufferedImage buffImg = ImageIO.read(file);
  28. // 获取层图
  29. BufferedImage waterImg = ImageIO.read(waterFile);
  30. // 创建Graphics2D对象,用在底图对象上绘图
  31. Graphics2D g2d = buffImg.createGraphics();
  32. int waterImgWidth = waterImg.getWidth();// 获取层图的宽度
  33. int waterImgHeight = waterImg.getHeight();// 获取层图的高度
  34. // 在图形和图像中实现混合和透明效果
  35. g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
  36. // 绘制
  37. g2d.drawImage(waterImg, x, y, waterImgWidth, waterImgHeight, null);
  38. g2d.dispose();// 释放图形上下文使用的系统资源
  39. return buffImg;
  40. }
  41. /**
  42. * 输出水印图片
  43. *
  44. * @param buffImg
  45. * 图像加水印之后的BufferedImage对象
  46. * @param savePath
  47. * 图像加水印之后的保存路径
  48. */
  49. private void generateWaterFile(BufferedImage buffImg, String savePath) {
  50. int temp = savePath.lastIndexOf(".") + 1;
  51. try {
  52. ImageIO.write(buffImg, savePath.substring(temp), new File(savePath));
  53. } catch (IOException e1) {
  54. e1.printStackTrace();
  55. }
  56. }
  57. /**
  58. *
  59. * @param args
  60. * @throws IOException
  61. * IO异常直接抛出了
  62. * @author bls
  63. */
  64. public static void main(String[] args) throws IOException {
  65. String sourceFilePath = "D://img//di.png";
  66. String waterFilePath = "D://img//ceng.png";
  67. String saveFilePath = "D://img//new.png";
  68. NewImageUtils newImageUtils = new NewImageUtils();
  69. // 构建叠加层
  70. BufferedImage buffImg = NewImageUtils.watermark(new File(sourceFilePath), new File(waterFilePath), 0, 0, 1.0f);
  71. // 输出水印图片
  72. newImageUtils.generateWaterFile(buffImg, saveFilePath);
  73. }
  74. }

版权声明:本文为bilaisheng原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/bilaisheng/p/10211056.html