来源:http://shensy.iteye.com/blog/1614153
package com.dxy.image;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
public class ImageAddWaterMark {
public static void main(String[] args) {
File originImgFile = new File("D:/image/1.jpg");
File watermarkImgFile = new File("D:/image/2.jpg");
File targetImgFile = new File("D:/image/3.jpg");
addWatermark(originImgFile,watermarkImgFile,targetImgFile);
}
/**
* 图片上加水印
* @param originImgFile 原图
* @param watermarkImgFile 水印图
* @param targetImgFile 输出文件
*/
public static File addWatermark(File originImgFile,File watermarkImgFile,File targetImgFile){
FileOutputStream fileOutputStream = null;
try {
//原图
Image originImage = ImageIO.read(originImgFile);
int originWidth = originImage.getWidth(null);//原图长
int originHeight = originImage.getHeight(null);//原图宽
//表示一个图像,它具有合成整数像素的 8位 RGB颜色分量.(以原图的长宽作为新图片的长宽)
BufferedImage image = new BufferedImage(originWidth,originHeight,BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();//获取Graphics以渲染BufferedImage
g.drawImage(originImage,0,0,originWidth,originHeight,null);//从渲染原图
//水印图
Image waterMarkImage = ImageIO.read(watermarkImgFile);
int waterMarkWidth = waterMarkImage.getWidth(null);//水印图长
int waterMarkHeight = waterMarkImage.getHeight(null);//水印图宽
//在原图指定位置渲染水印图(此处设置为右下角)
g.drawImage(waterMarkImage,(originWidth-waterMarkWidth),(originHeight-waterMarkHeight),waterMarkWidth,waterMarkHeight,null);
//释放此图形的上下文以及它使用的所有系统资源
g.dispose();
ImageWriter imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
imgWrier.reset();
fileOutputStream = new FileOutputStream(targetImgFile);//目标文件
imgWrier.setOutput(ImageIO.createImageOutputStream(fileOutputStream));
//IIOImage:聚集图像、缩略(预览)图像集和表示与图像关联的元数据对象的简单容器类
imgWrier.write(new IIOImage(image,null,null));
fileOutputStream.flush();
return targetImgFile;
}catch(Exception e){
e.printStackTrace();
}finally {
try{
if(fileOutputStream!=null) fileOutputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
return null;
}
}