最近项目中遇到个需求,图片去水印下载,由于上传时并未保存原图url,查找了相关资料,基本上都是通过设置RGB色值去水印,测试过后效果并不理想,会将图片中颜色跟RGB色值相同的也给去掉,在朋友的推荐下,使用了opecv这款开源软件,而Java调用opencv的例子很少,opencv官网上也没有java相关的api操作文档,期间踩了不少坑,最终在windows上测试通过,并在linux上也运行成功了(linux上效果更好),仅在这里记录下相关步骤,希望后续遇到同问题的人少走弯路。
opencv官网链接:https://opencv.org/releases/
这里以opencv-4.5.1为例。
cd opencv-4.5.1
mkdir build
cd build
apt install cmake
sudo apt-get install cmake
sudo apt-get install build-essential libgtk2.0-dev libavcodec-dev libavformat-dev libjpeg.dev libtiff4.dev libswscale-dev libjasper-dev
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -DBUILD_TESTS=OFF ..
make -j8
sudo make install
build/bin下有opencv-451.jar、build/lib下有libopencv_java451.so文件,表示安装成功
安装指定文件到本地仓库命令:mvn install:install-file
-Dfile= : 设置该jar包文件所在的路径与文件名
-DgroupId= : 设置上传到仓库的包名
-DartifactId= : 设置该包所属的模块名
-Dversion=1.0.0 : 设置该包的版本号
-Dpackaging=jar : 设置该包的类型(很显然jar包)
如:mvn install:install-file -Dfile=D:/opencv/opencv-451.jar -DgroupId=org.opencv -DartifactId=opencv -Dversion=4.5.1 -Dpackaging=jar
<!-- opencv -->
<dependency>
<groupId>org.opencv</groupId>
<artifactId>opencv</artifactId>
<version>4.5.1</version>
</dependency>
通过在application.yml文件中配置动态库路径,并增加配置类,完成配置。
1)application.yml配置如下;
opencv:
lib:
# linux
#path: /usr/local/environment/opencv/opencv-4.5.1/build/lib/libopencv_java451.so
#windows
path: D:/opencv/opencv/build/java/x64/opencv_java451.dll
2)配置类如下:
/**
* opencv动态库配置
* @author wangjiajin
* @date 2021/3/2
* @desc
*/
@Configuration
@ConfigurationProperties(prefix = "opencv.lib")
public class OpenCvLibConfig {
@Value("${opencv.lib.path}")
private String path;
@PostConstruct
public void init() {
System.load(path);
}
}
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 图片工具类
* @author wangjiajin
* @date 2021/2/23
* @desc
*/
public class ImageUtils {
public static void addWaterMark(String srcImgPath, String waterMarkContent, String waterImgPath) {
try {
// 读取原图片信息
File srcImgFile = new File(srcImgPath);//得到文件
Image srcImg = ImageIO.read(srcImgFile);//文件转化为图片
int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
int srcImgHeight = srcImg.getHeight(null);//获取图片的高
int fontSize = (srcImgWidth - 20) / waterMarkContent.length();
Font font = new Font("宋体", Font.PLAIN, fontSize);
// 加水印
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufImg.createGraphics();
g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
g.setColor(Color.white); //根据图片的背景设置水印颜色
g.setFont(font); //设置字体
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.4f));
//设置水印的坐标
int x = 10;
int y = (srcImgHeight) / 2;
g.drawString(waterMarkContent, x, y); //画出水印
g.dispose();
// 输出图片
FileOutputStream outImgStream = new FileOutputStream(waterImgPath);
ImageIO.write(bufImg, "jpg", outImgStream);
outImgStream.flush();
outImgStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void getMask(String path, String waterMarkContent, String maskPath) {
try {
Image originImg = ImageIO.read(new File(path));
int width = originImg.getWidth(null);
int height = originImg.getHeight(null);
int fontSize = (width - 20) / waterMarkContent.length();
Font font = new Font("宋体", Font.PLAIN, fontSize);
BufferedImage bufImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufImg.createGraphics();
g.setBackground(Color.BLACK);
g.clearRect(0, 0, width, height);
g.setColor(Color.white);
g.setFont(font);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.4f));
//设置水印的坐标
int x = 10;
int y = (height) / 2;
g.drawString(waterMarkContent, x, y); //画出水印
g.dispose();
// 输出图片
FileOutputStream outImgStream = new FileOutputStream(maskPath);
ImageIO.write(bufImg, "jpg", outImgStream);
outImgStream.flush();
outImgStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 给定一组url,将此集合地址下对应的资源下载到浏览器
*
* @param urls url地址的集合
* @throws IOException
*/
public static void downloadPic(java.util.List<String> urls, HttpServletResponse response) throws Exception {
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
try {
//文件的名称
String downloadFilename = "图片.zip";
//转换中文否则可能会产生乱码
downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
//指明response的返回对象是文件流
response.setContentType("application/octet-stream;charset=UTF-8");
//设置在下载框默认显示的文件名
response.setHeader("Content-Disposition","attachment;filename="+downloadFilename);
for (String url : urls) {
String imgName = LocalDateTime.now().toString();
String suffix = url.substring(url.lastIndexOf("."));
zos.putNextEntry(new ZipEntry(imgName + suffix));
InputStream fis = getInputStreamByGet(url);
byte[] bytes = new byte[1024];
int len;
while (true) {
assert fis != null;
if ((len = fis.read(bytes)) == -1) break;
zos.write(bytes, 0, len);
}
fis.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
zos.flush();
zos.close();
}
}
public static InputStream getInputStreamByGet(String url) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return conn.getInputStream();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
//1.启服务通过配置文件运行
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.photo.Photo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* opencv测试
* @author wangjiajin
* @date 2021/3/2
* @desc
*/
@RestController
@RequestMapping("/opencv")
@Api(tags = "opencv测试接口")
public class OpenCvTestController {
@PostMapping("/clearWater")
@ApiOperation(value = "图片去水印")
public String clearWater() {
String markContent = "测试生成水印";
String waterPath = "D:\\img\\water.jpg";
//通过原图加水印获得初始水印图
ImageUtils.addWaterMark("D:\\img\\1.png", markContent, waterPath);
//蒙版图路径
String maskPath = "D:\\img\\mask.jpg";
//获取蒙版图,黑底+透明水印字
ImageUtils.getMask(waterPath, markContent, maskPath);
//opencv读取水印图
Mat image = Imgcodecs.imread(waterPath);
//opencv读取蒙版
Mat mask = Imgcodecs.imread(maskPath, CvType.CV_8UC1);
Mat dst = new Mat(image.size(), CvType.CV_8UC3);
Photo.inpaint(image, mask, dst, 20, Photo.INPAINT_TELEA);
String originPath = "D:\\img\\test.jpg";
Imgcodecs.imwrite(originPath, dst);
return "成功";
}
}
//2.通过main方法测试
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.photo.Photo;
/**
* opencv图片去水印测试
* @author wangjiajin
* @date 2021/3/2
* @desc
*/
public class OpencvImageTest {
public static void main(String[] args) throws Exception {
//加载动态库,main方法无法通过配置文件加载
System.load("D:\\opencv\\opencv\\build\\java\\x64\\opencv_java451.dll");
String markContent = "测试生成水印";
String waterPath = "D:\\img\\water.jpg";
//通过原图加水印获得初始水印图
ImageUtils.addWaterMark("D:\\img\\1.png", markContent, waterPath);
//蒙版图路径
String maskPath = "D:\\img\\mask.jpg";
//获取蒙版图,黑底+透明水印字
ImageUtils.getMask(waterPath, markContent, maskPath);
//opencv读取水印图
Mat image = Imgcodecs.imread(waterPath);
if (image.empty()) {
throw new Exception("image is empty");
}
//opencv读取蒙版
Mat mask = Imgcodecs.imread(maskPath, CvType.CV_8UC1);
Mat dst = new Mat(image.size(), CvType.CV_8UC3);
Photo.inpaint(image, mask, dst, 20, Photo.INPAINT_TELEA);
HighGui.imshow("原图", image);
HighGui.imshow("蒙版", mask);
HighGui.imshow("结果", dst);
String originPath = "D:\\img\\test.jpg";
Imgcodecs.imwrite(originPath, dst);
HighGui.waitKey();
}
}
org.opencv.imgcodecs.Imgcodecs.imread_1(Ljava/lang/String;)J
//解决方法,将pom中热部署依赖去掉即可
<!-- 热部署 -->
<!--<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>-->