SpringBoot使用maven打包opencv时无法打包以及运行相关问题

437 阅读1分钟

在本地可以使用opencv相关函数,但打包失败

所报错误为:opencv程序包不存在

解决方案: 1.将opencv的jar包放到本地maven仓库中

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=jar

2.再使用常规的dependency在pom文件中导入依赖

<dependency>  
    <groupId>org.opencv</groupId>  
    <artifactId>opencv</artifactId>  
    <version>4.4.0</version>  
</dependency>

此时进行打包即可成功

打包后使用命令行(win环境)运行失败

失败原因为直接对opencv.dll进行加载(本地环境)

URL url = ClassLoader.class.getResource("/opencv_java440.dll");

解决方案:在运行jar包时将dll文件解压到缓存中

InputStream in = AppRun.class.getResourceAsStream("/opencv_java440.dll");  
System.out.println("MainTest.class.getClass()" + in);  
  
File ffile = new File("");  
String filePath = null;  
filePath = ffile.getAbsolutePath() + File.separator + "/opencv_java440.dll";  
File dll = new File(filePath);  
FileOutputStream out = new FileOutputStream(dll);    
int i;  
byte[] buf = new byte[1024];  
try {  
    while ((i = in.read(buf)) != -1) {  
        out.write(buf, 0, i);  
    }  
} finally {  
    in.close();  
    out.close();  
}  
System.load(dll.getAbsolutePath());
dll.deleteOnExit();

注:若需要部署到linux环境则使用so文件