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;
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();
}
}
public static void main(String[] args)
{
WaterMark waterMark = new WaterMark();
if(args.length == 2)
{
waterMark.imgMark(args[0],args[1]);
}
else
{
System.out.println("Java WaterMark fileOriginal fileWaterMark");
}
}
}