给图片加水印


  1. import java.awt.Color;
  2. import java.awt.Font;
  3. import java.awt.Graphics2D;
  4. import java.awt.Image;
  5. import java.awt.image.BufferedImage;
  6. import java.io.File;
  7. import java.io.FileOutputStream;
  8. import javax.imageio.ImageIO;
  9. /**
  10. *
  11. * @use java给图片添加水印文字
  12. * @ProjectName stuff
  13. * @Author <a href="mailto:mhmyqn@qq.com">mumaoqiang</a></br>
  14. * @Date 2012-7-19 下午10:27:54 </br>
  15. * @FullName com.mmq.watermark.WaterMarkUtils.java </br>
  16. * @JDK 1.6.0 </br>
  17. * @Version 1.0 </br>
  18. */
  19. public class WaterMarkUtils {
  20. /**
  21. * 图片添加水印
  22. * @param srcImgPath 需要添加水印的图片的路径
  23. * @param outImgPath 添加水印后图片输出路径
  24. * @param markContentColor 水印文字的颜色
  25. * @param waterMarkContent 水印的文字
  26. */
  27. public void mark(String srcImgPath, String outImgPath, Color markContentColor, String waterMarkContent) {
  28. try {
  29. // 读取原图片信息
  30. File srcImgFile = new File(srcImgPath);
  31. Image srcImg = ImageIO.read(srcImgFile);
  32. int srcImgWidth = srcImg.getWidth(null);
  33. int srcImgHeight = srcImg.getHeight(null);
  34. // 加水印
  35. BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
  36. Graphics2D g = bufImg.createGraphics();
  37. g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
  38. //Font font = new Font("Courier New", Font.PLAIN, 12);
  39. Font font = new Font("宋体", Font.PLAIN, 50);
  40. g.setColor(markContentColor); //根据图片的背景设置水印颜色
  41. g.setFont(font);
  42. int x = srcImgWidth - getWatermarkLength(waterMarkContent, g) - 3;
  43. int y = srcImgHeight - 3;
  44. //int x = (srcImgWidth - getWatermarkLength(watermarkStr, g)) / 2;
  45. //int y = srcImgHeight / 2;
  46. g.drawString(waterMarkContent, x, y);
  47. g.dispose();
  48. // 输出图片
  49. FileOutputStream outImgStream = new FileOutputStream(outImgPath);
  50. ImageIO.write(bufImg, "jpg", outImgStream);
  51. outImgStream.flush();
  52. outImgStream.close();
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. /**
  58. * 获取水印文字总长度
  59. * @param waterMarkContent 水印的文字
  60. * @param g
  61. * @return 水印文字总长度
  62. */
  63. public int getWatermarkLength(String waterMarkContent, Graphics2D g) {
  64. return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
  65. }
  66. public static void main(String[] args) {
  67. // 原图位置, 输出图片位置, 水印文字颜色, 水印文字
  68. new WaterMarkUtils().mark("d:/postWatermark.jpg", "d:/afterWatermark.jpg", Color.red, "水印效果测试");
  69. }
  70. }