在51cto写博文上传图片的时候,觉得图片上加上水印很有意思,与是有了自己动手写一个加水印的小程序,自己动手丰衣足食。来看看我写的代码吧,哈哈


  1. package com.sucre.blog;  
  2.  
  3. import java.awt.Color;  
  4. import java.awt.Font;  
  5. import java.awt.Graphics2D;  
  6. import java.awt.Image;  
  7. import java.awt.p_w_picpath.BufferedImage;  
  8. import java.io.FileOutputStream;  
  9.  
  10. import javax.swing.ImageIcon;  
  11.  
  12. import com.sun.p_w_picpath.codec.jpeg.JPEGCodec;  
  13. import com.sun.p_w_picpath.codec.jpeg.JPEGEncodeParam;  
  14. import com.sun.p_w_picpath.codec.jpeg.JPEGImageEncoder;  
  15. /**  
  16.  * 给图片加水印  
  17.  * @author sucre  
  18.  *  
  19.  */ 
  20. public class ProductWaterMark {  
  21.     public boolean createMark(String filePath, String markContent,  
  22.             Color markContentColor, float qualNum, String watermark) {  
  23.         ImageIcon imgIcon = new ImageIcon(filePath);  
  24.         Image theImg = imgIcon.getImage();  
  25.         int width = theImg.getWidth(null);  
  26.         int height = theImg.getHeight(null);  
  27.         BufferedImage bp_w_picpath = new BufferedImage(width, height,  
  28.                 BufferedImage.TYPE_INT_RGB);  
  29.         Font font = new Font("新宋体", Font.PLAIN, 50);//这里控制图片上文字的大小  
  30.         Graphics2D g = bp_w_picpath.createGraphics();  
  31.         g.setColor(markContentColor);  
  32.         g.setFont(font);  
  33.         g.setBackground(Color.white);  
  34.         g.drawImage(theImg, 00null);  
  35.         //添加水印的文字和设置水印文字出现的内容  
  36.         g.drawString(markContent, width - 800, height - 80);   
  37.         g.dispose();  
  38.         try {  
  39.             FileOutputStream out = new FileOutputStream(filePath);  
  40.             JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
  41.             JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bp_w_picpath);  
  42.             param.setQuality(qualNum, true);  
  43.             encoder.encode(bp_w_picpath, param);  
  44.             out.close();  
  45.         } catch (Exception e)  
  46.         {  
  47.             return false;  
  48.         }  
  49.         return true;  
  50.     }  
  51.  
  52.     public static void main(String arg[]) {  
  53.         ProductWaterMark wk = new ProductWaterMark();  
  54.         boolean successOrNot = wk.createMark("F:\\我的图片\\1.jpg","http://sucre.blog.51cto.com", Color.BLACK, 23f, "");  
  55.         System.out.println(successOrNot?"You are Success!":"You are Failure");  
  56.     }  
  57. }  

无水印的图

 

给图片加水印

加水印后的图片

 

给图片加水印

看到了吧,图片的最小方有一行大黑字,虽然没有博客系统加的好看,但是我觉得还行。