为图片添加水印
/**
* 添加水印
* @param imagePath 图片绝对路径
* @param watermarkPath 水印图片绝对路径
* @param position 水印图片位置
* @return 生成水印图片的绝对路径
*/
public static String addWatermark(String imagePath, String watermarkPath, String position) {
logger.info("为图片({})在位置{}添加水印({})", imagePath, position, watermarkPath);
if (StringUtils.isNotBlank(imagePath) && StringUtils.isNotBlank(watermarkPath)) {
File image = new File(imagePath);
File watermark = new File(watermarkPath);
Position pos = getPostion(position);
if (image.isFile() && image.exists() && watermark.isFile()) {
try {
BufferedImage bi = ImageIO.read(image);
Builder<File> builder = Thumbnails.of(imagePath);
BufferedImage watermarkImg = ImageIO.read(watermark);
File newWatermark = null;
// 原图的宽或高是水印图片宽或高的2倍及以上,则直接打上水印原图;否则缩略水印图片,以原图宽或高的二分之一
if (bi.getWidth() / watermarkImg.getWidth() <= 2 || bi.getHeight() / watermarkImg.getHeight() <= 2) {
newWatermark = genNewWatermark(watermarkPath, bi.getWidth() / 2, bi.getHeight() / 2);
watermarkImg = ImageIO.read(newWatermark);
}
builder.size(bi.getWidth(), bi.getHeight());
if(bi.getType() == BufferedImage.TYPE_BYTE_INDEXED){
builder.imageType(BufferedImage.TYPE_INT_ARGB);
}
if(pos instanceof Coordinate){
serialWatermark(builder, bi, watermarkImg);
}else{
builder.watermark(pos, watermarkImg, Float.valueOf(PropertyUtil.get("watermarkOpacity")));// watermark(位置,水印图,透明度)
}
String newImagePath = generateNewFilePath(imagePath);
builder.outputQuality(Float.valueOf(PropertyUtil.get("watermarkQuality"))).toFile(newImagePath);// 保存水印图的质量0-1
if (newWatermark != null) {
newWatermark.delete();
}
return newImagePath;
} catch (Exception e) {
logger.error("水印图片出错", e);
return null;
}
} else {
logger.error("图片或者水印不存在");
return null;
}
} else {
logger.error("图片或者水印参数为null");
return null;
}
}
评论