第一种方法:Graphics ,剧中显示水印,但是不会随着图片大小缩放,适应场景:大小一样的图片或者差不多的图片
/**
* watermarkImg-- 水印文件
* targetImg -- 目标文件
*/
public final static void pressImage(String watermarkImg, String targetImg) {
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 graphics = image.createGraphics();
graphics.drawImage(src, 0, 0, wideth, height, null);
File fileWatermark = new File(watermarkImg);
Image src_Watermark = ImageIO.read(fileWatermark );
int wideth_Watermark = src_Watermark.getWidth(null);
int height_Watermark = src_Watermark.getHeight(null);
graphics.drawImage(src_Watermark, wideth - wideth_Watermark - ((wideth - wideth_Watermark)/2), height - height_Watermark -((height - height_Watermark)/2), wideth_Watermark,
height_Watermark, null);//设置剧中印刷
graphics.dispose();
String formatName = targetImg.substring(targetImg.lastIndexOf(".") + 1);
ImageIO.write(image, /*"GIF"*/ formatName /* format desired */ , new File(targetImg) /* target */ );
} catch (Exception e) {
e.printStackTrace();
}
}
第二种:Thumbnails 会随着图片的大小缩放水印图片, bl会根据水印图片的大小变化,需要自己试验一下
/**
*watermarkImg-- 水印文件
* targetImg -- 目标文件
*/
public final static void pressImage(String watermarkImg, 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);
// 水印文件
File fileWatermark = new File(watermarkImg);
Image src_Watermark = ImageIO.read(fileWatermark);
double bl = 0.2;
if(wideth >=300 && wideth<400){
bl =0.5;//水印为原图宽高比例 px 300->400
}else if(wideth >=400 && wideth<500){
bl =0.7;//水印为原图宽高比例 px 400->500
}else if(wideth >=500 && wideth<600){
bl =0.9;//水印为原图宽高比例 px 500->600
}else if(wideth >=600 && wideth<700){
bl =1;//水印为原图宽高比例 px 600->700
}else if(wideth >=600 && wideth<700){
bl =1;//水印为原图宽高比例 px 700->800
}else if(wideth >=700 && wideth<800){
bl =1.1;//水印为原图宽高比例 px 700->800
}else if(wideth >=800){
bl =1.2;//水印为原图宽高比例 px 800->900
}
int widthOld = (int) (src_Watermark .getWidth(null) * bl);
int heightOld = widthOld * src_Watermark.getHeight(null) / src_Watermark.getWidth(null);
//读取水印图
//URL url = FileUnitTest.class.getResource();
//生成新的水印图
BufferedImage bufferedImage = Thumbnails.of(watermarkImg).size(widthOld,heightOld).keepAspectRatio(false).asBufferedImage();
Thumbnails.of(_file).watermark(Positions.CENTER, bufferedImage, 1f).scale(1).toFile(targetImg);
} catch (Exception e) {
e.printStackTrace();
}
}