在平時的web項目中咱們可能須要在圖片上加一些屬於本身的東西,就像weibo發圖片會帶有微博名的水印,這個功能能夠用在咱們的web項目中,這樣咱們的圖片將會不同凡響。下面是實現該功能的代碼java
這個是主要的類web
1 package ciacs.picture.test; 2 import java.awt.Color; 3 import java.awt.Font; 4 import java.awt.Graphics; 5 import java.awt.Image; 6 import java.awt.image.BufferedImage; 7 import java.io.FileOutputStream; 8 9 import javax.swing.ImageIcon; 10 11 import com.sun.image.codec.jpeg.JPEGCodec; 12 import com.sun.image.codec.jpeg.JPEGImageEncoder; 13 14 /* 15 * @author:CIACs 16 * 17 */ 18 19 20 public class WaterMark{ 21 22 public boolean addMark(String file) 23 { 24 boolean flag=true; 25 26 String str = "http://www.cnblogs.com/zhi-hao/"; 27 try 28 { 29 ImageIcon imgIcon=new ImageIcon(file); 30 Image img = imgIcon.getImage(); 31 int width = img.getWidth(null); 32 int height = img.getHeight(null); 33 //create target image 34 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 35 //get a graphics pen 36 Graphics g = image.createGraphics(); 37 //draw source image 38 g.drawImage(img, 0, 0, width, height, null); 39 40 //能夠改變畫筆的顏色 41 42 g.setColor(Color.blue); 43 //能夠設置你要的字體、顏色、大小 44 g.setFont(new Font("Courier", Font.PLAIN, 23)); 45 //設置水印出如今圖片的位置 46 g.drawString(str, 280, height-23); 47 g.dispose(); 48 FileOutputStream os = new FileOutputStream(file); 49 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os); 50 encoder.encode(image); 51 52 }catch(Exception e) 53 { 54 System.out.println(e.getMessage()); 55 flag=false; 56 } 57 return flag; 58 } 59 60 }
下面這個是測試類測試
1 package ciacs.picture.test; 2 3 public class test{ 4 5 public static void main(String[] args) { 6 WaterMark mark = new WaterMark(); 7 //添加的爲圖片所在的路徑 8 mark.addMark("D:/test.png"); 9 10 11 12 } 13 14 }
結果:字體
這個加水印的功能稍加修改就能夠做爲組件提供給咱們的web項目中使用。spa