这是个很常用的操作,一般我们的网站在用户上传图片时都会给图片添加一个水印以防止其他站点盗图的行为
实现功能:①给图片增加文字水印②给图片增加图片水印
一、核心功能实现:
1、添加文字水印
// 加文字水印
public void mark(BufferedImage bufImg, Image img, String text, Font font, Color color, int x, int y) {
Graphics2D g = bufImg.createGraphics();
g.drawImage(img, 0, 0, bufImg.getWidth(), bufImg.getHeight(), null);
g.setColor(color);
g.setFont(font);
g.drawString(text, x, y);
g.dispose();
}
2、添加图片水印
// 加图片水印
public void mark(BufferedImage bufImg, Image img, Image markImg, int width, int height, int x, int y) {
Graphics2D g = bufImg.createGraphics();
g.drawImage(img, 0, 0, bufImg.getWidth(), bufImg.getHeight(), null);
g.drawImage(markImg, x, y, width, height, null);
g.dispose();
}
以上两个方法实现了最核心的功能:给图片添加水印。
补充:
为什么要这么写?
考虑到该方法不仅可以用于给图片文件增加水印,而且还可以给视频的每一帧图像也添加,所以为了方便不同场合重复使用,去除了不必要的依赖关系。
有了核心的两个方法就我们可以给图片文件增加水印了
二、功能性实现
1、给图片增加文字水印
/**
* 给图片增加文字水印
*
* @param imgPath
* -要添加水印的图片路径
* @param outImgPath
* -输出路径
* @param text-文字
* @param font
* -字体
* @param color
* -颜色
* @param x
* -文字位于当前图片的横坐标
* @param y
* -文字位于当前图片的竖坐标
*/
public void mark(String imgPath, String outImgPath, String text, Font font, Color color, int x, int y) {
try {
// 读取原图片信息
File imgFile = null;
Image img = null;
if (imgPath != null) {
imgFile = new File(imgPath);
}
if (imgFile != null && imgFile.exists() && imgFile.isFile() && imgFile.canRead()) {