package com.page;
import java.io.File;
import java.io.FileOutputStream;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 图片水印
* waterMark.imgMark(原始文件路径, 水印文件路径);
* 透明水印,将水印图片设置为透明背景就可以了(png格式)
*/
public class WaterMark {
public void imgMark(String strOriginalFileName, String strWaterMarkFileName) {
try {
// 源文件
File fileOriginal = new File(strOriginalFileName);
Image imageOriginal = ImageIO.read(fileOriginal);
int widthOriginal = imageOriginal.getWidth(null);
int heightOriginal = imageOriginal.getHeight(null);
// System.out.println("widthOriginal:" + widthOriginal
// + "\theightOriginal:" + heightOriginal);
BufferedImage bufImage = new BufferedImage(widthOriginal,
heightOriginal, BufferedImage.TYPE_INT_RGB);
Graphics g = bufImage.createGraphics();
g.drawImage(imageOriginal, 0, 0, widthOriginal, heightOriginal,
null);
// 水印文件
File fileWaterMark = new File(strWaterMarkFileName);
Image imageWaterMark = ImageIO.read(fileWaterMark);
int widthWaterMark = imageWaterMark.getWidth(null);
int heightWaterMark = imageWaterMark.getHeight(null);
// System.out.println("widthWaterMark:" + widthWaterMark
// + "\theightWaterMark:" + heightWaterMark);
// 水印文件在源文件的右下角
g.drawImage(imageWaterMark, widthOriginal - widthWaterMark,
heightOriginal - heightWaterMark, widthWaterMark,
heightWaterMark, null);
g.dispose();
FileOutputStream fos = new FileOutputStream(strOriginalFileName);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
encoder.encode(bufImage);
fos.flush();
fos.close();
fos = null;
} catch (Exception e) {
e.printStackTrace();
System.out.println("++WaterMark-Build the watermark fail.");
}
}
// 测试
public static void main(String[] args) {
WaterMark waterMark = new WaterMark();
waterMark.imgMark("d:/t3.jpg", "d:/watermark.png");
}
}
以上代码来自网络