今天有個學(xué)生說,他想把他上傳的圖片加上個水印的功能,以防止別人盜用他的圖片。他認(rèn)為他的圖片資料很重要。所以。。。
好,有需求,我們就滿足他,以前我也比較少寫操作圖片的api,所以對圖片加水印的功能也一直沒接觸,不過對于現(xiàn)在網(wǎng)絡(luò)來說。這些根本就不算什么,上網(wǎng)一搜,就找了幾個程序出來,現(xiàn)在我重構(gòu)了下,使它滿足我的要求,現(xiàn)在發(fā)布出來,希望可以給有需要的朋友一點(diǎn)幫助。
java 代碼
-
public final class ImageUtils {
-
public ImageUtils() {
-
-
}
-
-
public final static String getPressImgPath(){
-
return ApplicationContext.getRealPath("/template/data/util/shuiyin.gif");
-
}
-
-
-
-
-
-
-
-
-
public final static void pressImage(String pressImg, String targetImg, int x, int y) {
-
try {
-
File _file = new File(targetImg);
-
Image src = ImageIO.read(_file);
-
int wideth = src.getWidth(null);
-
int height = src.getHeight(null);
-
BufferedImage image = new BufferedImage(wideth, height,
-
BufferedImage.TYPE_INT_RGB);
-
Graphics g = image.createGraphics();
-
g.drawImage(src, 0, 0, wideth, height, null);
-
-
-
File _filebiao = new File(pressImg);
-
Image src_biao = ImageIO.read(_filebiao);
-
int wideth_biao = src_biao.getWidth(null);
-
int height_biao = src_biao.getHeight(null);
-
g.drawImage(src_biao, wideth - wideth_biao - x, height - height_biao -y, wideth_biao,
-
height_biao, null);
-
-
g.dispose();
-
FileOutputStream out = new FileOutputStream(targetImg);
-
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
-
encoder.encode(image);
-
out.close();
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
public static void pressText(String pressText, String targetImg, String fontName,int fontStyle, int color, int fontSize, int x, int y) {
-
try {
-
File _file = new File(targetImg);
-
Image src = ImageIO.read(_file);
-
int wideth = src.getWidth(null);
-
int height = src.getHeight(null);
-
BufferedImage image = new BufferedImage(wideth, height,
-
BufferedImage.TYPE_INT_RGB);
-
Graphics g = image.createGraphics();
-
g.drawImage(src, 0, 0, wideth, height, null);
-
-
g.setColor(Color.RED);
-
g.setFont(new Font(fontName, fontStyle, fontSize));
-
-
-
g.drawString(pressText, wideth - fontSize - x, height - fontSize/2 - y);
-
g.dispose();
-
FileOutputStream out = new FileOutputStream(targetImg);
-
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
-
encoder.encode(image);
-
out.close();
-
} catch (Exception e) {
-
System.out.println(e);
-
}
-
}
-
-
public static void main(String[] args) {
-
pressImage("C:/shuiyin/shuiyin.gif", "c:/shuiyin/DSC02342.JPG", 20 ,20);
-
}
-
}
(責(zé)任編輯:代碼如詩) |