SpringBoot给图片加图片logo水印
http://www.zeromemos.com/index/article/read.html?id=345
接着文字logo,给上面链接中的工具类加上添加logo水印的方法,完整工具类会放文末下载
/**
* 给图片添加水印logo
* @param logo logo文件位置
* @param inputStream 源图片路径
* @param outputStream 目标图片路径
* @param degree 水印旋转
* @param typeName 文件后缀名
*/
public static void markLogoImageByIO(String logo, InputStream inputStream, OutputStream outputStream,
Integer degree, String typeName) {
try {
// 1、源图片
Image srcImg = ImageIO.read(inputStream);
int imgWidth = srcImg.getWidth(null);
int imgHeight = srcImg.getHeight(null);
BufferedImage buffImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
// 2、得到画笔对象
Graphics2D g = buffImg.createGraphics();
// 3、把源图先画上
g.drawImage(srcImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);
// 4、读取水印图片
File fileLogo = new File(logo);
Image imgLogo = ImageIO.read(fileLogo);
// 5、读取水印的宽高
int logoWidth = imgLogo.getWidth(null);
int logoHeight = imgLogo.getHeight(null);
// 6、设置水印旋转
if (null != degree) {
g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
}
// 7、设置水印透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
// 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
g.drawImage(imgLogo, imgWidth - logoWidth - 20, imgHeight - logoHeight - 20, null);
// 9、释放资源
g.dispose();
// 10、生成图片
ImageIO.write(buffImg, typeName.toUpperCase(), outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
Controller里添加测试方法
@Autowired
private WaterMarkUtil waterMarkUtil;
//图片水印
@PostMapping("/watermark")
public R watermark(MultipartFile photo){
//如果非空
if (!photo.isEmpty()){
//获取文件名
String originalFilename = photo.getOriginalFilename();
//获取文件后缀
int length = originalFilename.length();
String typeName = originalFilename.substring(originalFilename.indexOf(".")+1, length);
//文件保存路径
String fileName = "C:\\Users\\admin\\Desktop\\" + originalFilename;
File targetFile = new File(fileName);
//水印logo文件位置
String logo = "C:\\Users\\admin\\Desktop\\logo.png";
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = photo.getInputStream();
outputStream = new FileOutputStream(targetFile);
//使用工具类添加水印
waterMarkUtil.markLogoImageByIO(logo, inputStream, outputStream, 0, typeName);
outputStream.close();
inputStream.close();
System.out.println("*****图片上传成功*****");
return R.ok().data("info", "图片上传成功");
} catch (IOException e) {
e.printStackTrace();
}
}
return R.error();
}
测试结果如下(水印位置右下角):