java调用python脚本

有时候需要在java代码中调用python脚本来完成某些功能,如何调用呢?

最简单的方式就是使用java代码,运行python命令,执行python脚本,具体如下:

Java代码 

public static void main(String[] args) {
		Process proc;
		try {
			proc = Runtime.getRuntime().exec("python f:\\FaceAPI.py");
			BufferedReader in = proc.inputReader();
			BufferedReader errorReader = proc.errorReader();
			String line = null;
			while ((line = in.readLine()) != null) {
				System.out.println(line);
			}
			while ((line = errorReader.readLine()) != null) {
				System.out.println(line);
			}
			in.close();
			errorReader.close();
			proc.waitFor();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

FaceAPI.py

import requests
import base64

'''
人像动漫化
'''

request_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime"
# 二进制方式打开图片文件
img_url = 'f:\\1.jpeg'
f = open(img_url,'rb')
img = base64.b64encode(f.read())

params = {"image":img}
access_token = '24.12480192df9bf2cef461fc6040b4eaef.2592000.1656638033.282335-26356057'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
if response:
    # print (response.json())
    data = base64.b64decode(response.json()['image'])
    #print(data)
    f1 = open(img_url,'wb')
    f1.write(data)
    f1.close()
    print('ren lian dong man hua chenggong!')

运行结果:

 注意:安装python时,

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值