給圖片加浮水印的Java代碼

來源:互聯網
上載者:User
原理還是比較簡單的,利用java.awt.Image和javax.imageio.ImageIO類讀入待處理的圖片,自己new一個新的
java.awt.image.BufferedImage建立一個java.awt.Graphics出來,利用它就可以為所欲為隨便亂畫叻,哈哈,然
後用com.sun.image.codec.jpeg.JPEGCodec和
com.sun.image.codec.JPEGImageEncoder輸出為.jpg檔案即可。

需要注意的是異常處理,以及ImageIO.read()方法後變數的null判斷,因為檔案可能不存在,也可能不是個圖片檔案。

相關代碼:

Code:


/*

* Created on 2005-8-23

*

*/

package cn.edu.sjtu.se.elearning.util;



import java.awt.Graphics;

import java.awt.Image;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.FileOutputStream;



import javax.imageio.ImageIO;



import com.sun.image.codec.jpeg.JPEGCodec;

import com.sun.image.codec.jpeg.JPEGImageEncoder;



/**

* @author hongliang

* 

*/

public class Test {



public static void main(String[] args) throws Throwable {

//get source image

Image img = ImageIO.read(new File("/home/hongliang/a.png"));

int width = img.getWidth(null);

int height = img.getHeight(null);



//create target image

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

//get a graphics pen

Graphics g = image.createGraphics();



//draw source image

g.drawImage(img, 0, 0, width, height, null);



//draw target logo

Image logo = ImageIO.read(new File("/home/hongliang/4x.gif"));

int lw = logo.getWidth(null);

int lh = logo.getHeight(null);

g.drawImage(logo, width-lw, height-lh, lw, lh, null);

//如果不想加圖片浮水印,而是文字,則是這裡的代碼

// String str = "http://www.hongliang.net";

// g.setColor(Color.BLUE);

// g.setFont(new Font("Courier", Font.PLAIN, 36));

//這裡的文字位置要研究一番,容易對不準

// g.drawString(str, width-360, height-72);

g.dispose();



FileOutputStream os = new FileOutputStream("/home/hongliang/b.jpg");

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);

encoder.encode(image);

}

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.