轉:Java新增水印(圖片水印,文字水印)

herosoft發表於2010-03-06
JAVA/JSP在圖片中新增文字或在圖片中新增圖片.[@more@]

imp<wbr>ort java.awt.Color;
imp<wbr>ort java.awt.Font;
imp<wbr>ort java.awt.Graphics;
imp<wbr>ort java.awt.Image;
imp<wbr>ort java.awt.image.BufferedImage;
imp<wbr>ort java.io.File;
imp<wbr>ort java.io.FileOutputStream;
imp<wbr>ort javax.imageio.ImageIO;
imp<wbr>ort com.sun.image.codec.jpeg.JPEGCodec;
imp<wbr>ort com.sun.image.codec.jpeg.JPEGImageEncoder;

public final class ImageUtils {
public ImageUtils() {

}

/**//*
* public final static String getPressImgPath() { return ApplicationContext
* .getRealPath("/template/da<wbr>ta/util/shuiyin.gif"); }
*/

/** *//**
* 把圖片印刷到圖片上
*
* @param pressImg --
* 水印檔案
* @param targetImg --
* 目標檔案
* @param x
* --x座標
* @param y
* --y座標
*/
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) / 2,
(height - height_biao) / 2, 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();
}
}

/** *//**
* 列印文字水印圖片
*
* @param pressText
* --文字
* @param targetImg --
* 目標圖片
* @param fontName --
* 字型名
* @param fontStyle --
* 字型樣式
* @param color --
* 字型顏色
* @param fontSize --
* 字型大小
* @param x --
* 偏移量
* @param y
*/

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);
// String s="";
g.setColor(new Color(color,false));
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) {
pressText("李白杜","e:1.jpg","font-weight", Font.BOLD,255,70,700, 100);
pressImage("e:/2.png", "e:/1.jpg", 0, 0);

}
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/220284/viewspace-1031616/,如需轉載,請註明出處,否則將追究法律責任。

相關文章