How to package opencv +java in a jar

后端 未结 1 1438
攒了一身酷
攒了一身酷 2020-12-10 06:43

I\'ve been using Opencv 2.4.5 with Java for a while building an application and would now like to distribute the app. The library is loaded using the following:



        
相关标签:
1条回答
  • 2020-12-10 07:48

    As Steven C said, it was as in Extract and load DLL from JAR and also in a bug report. I was slightly ignorant of how to use dylibs and was trying to be consistent with an OpenCV tutorial which used a "user library" to add a jar, and then add the native dylib. Also, for some reason loading resources even when using "/" was loading from the src directory, not my project's root directory (which was the case in a test project I made).

    For those trying to do the same thing, here's some code to help:

    private static void loadLibrary() {
        try {
            InputStream in = null;
            File fileOut = null;
            String osName = System.getProperty("os.name");
            Utils.out.println(Main.class, osName);
            if(osName.startsWith("Windows")){
                int bitness = Integer.parseInt(System.getProperty("sun.arch.data.model"));
                if(bitness == 32){
                    Utils.out.println(Main.class, "32 bit detected");
                    in = Main.class.getResourceAsStream("/opencv/x86/opencv_java245.dll");
                    fileOut = File.createTempFile("lib", ".dll");
                }
                else if (bitness == 64){
                    Utils.out.println(Main.class, "64 bit detected");
                    in = Main.class.getResourceAsStream("/opencv/x64/opencv_java245.dll");
                    fileOut = File.createTempFile("lib", ".dll");
                }
                else{
                    Utils.out.println(Main.class, "Unknown bit detected - trying with 32 bit");
                    in = Main.class.getResourceAsStream("/opencv/x86/opencv_java245.dll");
                    fileOut = File.createTempFile("lib", ".dll");
                }
            }
            else if(osName.equals("Mac OS X")){
                in = Main.class.getResourceAsStream("/opencv/mac/libopencv_java245.dylib");
                fileOut = File.createTempFile("lib", ".dylib");
            }
    
    
            OutputStream out = FileUtils.openOutputStream(fileOut);
            IOUtils.copy(in, out);
            in.close();
            out.close();
            System.load(fileOut.toString());
        } catch (Exception e) {
            throw new RuntimeException("Failed to load opencv native library", e);
        }
    
    0 讨论(0)
提交回复
热议问题