前提环境:
操作系统:MAC OS
Python脚本:OpenCV中最简单的图像缩放程序
java运行环境:Springboot+IDEA+jdk1.8
话不多说,直接上一开始执行代码
//测试代码
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.*;
@SpringBootTest
class LayuiApplicationTests {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Test
void contextLoads() {
int a = 3;
int b = 2;
try {
String[] arg = new String[]{"python3", "src/main/resources/python/sizeChange.py",String.valueOf(a), String.valueOf(b)};
Process pr = Runtime.getRuntime().exec(arg);
final InputStream is1 = pr.getInputStream();
new Thread(() -> {
BufferedReader br = new BufferedReader(new InputStreamReader(is1));
try{
while(br.readLine() != null) ;
}
catch(Exception e) {
e.printStackTrace();
}
}).start();
InputStream is2 = pr.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is2));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
int re = pr.waitFor();
in.close();
if (re == 1) {
logger.info("调用脚本失败");
} else {
logger.info("调用脚本成功");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Python脚本代码:
import cv2
import sys
def func(a,b):
src = cv2.imread('src/main/resources/python/logo.jpg',3)
res = cv2.resize(src, None, fx=a, fy=b, interpolation = cv2.INTER_CUBIC)
cv2.imwrite('src/main/resources/python/res.jpg',res)
if __name__ == '__main__':
a = []
for i in range(1, len(sys.argv)):
a.append((int(sys.argv[i])))
func(a[0],a[1])
从主程序传参到Python程序中调用
起先一开始死活运行不出来图片结果,明明在终端执行python /xxx/xxx.py全路径名称都能 成功执行,到这就一直执行不出结果,后来查遍几乎所有跟Runtime.getRuntime().exec有关的资料。。问题发现了
由于Mac自带Python版本是Python2,即使你已经在外面把Mac版本改为3,但通过Runtime.getRuntime().exec调用Python脚本时依旧会以2为基础执行(咱也不知道为什么),导致执行错误,所以要把命令改为python3,这里的is1、is2用来解决进程阻塞执行不出结果的问题,去掉后也可以照常执行,出问题加上就好了
以下是最简洁的执行代码:
@Test
void contextLoads() {
int a = 3;
int b = 2;
try {
String[] arg = new String[]{"python3", "src/main/resources/python/sizeChange.py",String.valueOf(a), String.valueOf(b)};
Process pr = Runtime.getRuntime().exec(arg);
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
int re = pr.waitFor();
in.close();
if (re == 1) {
logger.info("调用脚本失败");
} else {
logger.info("调用脚本成功");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Windows估计就没那么多事了。。Mac还是要注意一下差别