一、JAVA
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String result=ocr();
System.out.println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String ocr() throws Exception{
String serverURL = "http://127.0.0.1:7809/ocr";
String path = "D://222.png";
String result="";
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(serverURL);
// 默认的的ContentType是application/octet-stream
FileBody bin = new FileBody(new File(path))
//添加附件参数,一定要要是文件格式,否则字符串文件流Python无法解析
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("img", bin).build();//添加参数
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
response.close();
httpclient.close();
if (statusCode == HttpStatus.SC_OK) {
result= EntityUtils.toString(resEntity);
} else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
result="上传文件发生异常,请检查服务端异常问题";
}
return result;
}
二、PYHTON服务端
#-*-coding:utf8-*- import sys reload(sys) sys.setdefaultencoding('utf-8') import flask from flask import request #想获取到请求参数的话,就得用这个 import Chat import Ocr import Common import os server = flask.Flask(__name__) '''图片转文字''' @server.route('/ocr',methods=['get','post']) def ocr(): #根据request获取文件,不可以接收字节字符串,即无法接收文件流 img=request.files["img"] print os.path.splitext(img.filename) #获取随机文件名 temp=Common.randomcode()+os.path.splitext(img.filename)[1] print img.filename path=os.path.join('./images/temp',temp) print path #将文件临时存储至缓存路径,不可以直接将获取到的文件读取,必须先存储再读取 img.save(path) result=Ocr.get_texts(path) #移除临时文件 os.remove(path) return result if __name__ == "__main__": server.run('127.0.0.1', 7809, debug=False)
2、ocr源码
#-*-coding:utf8-*- import sys reload(sys) sys.setdefaultencoding('utf-8') from aip import AipOcr APP_ID = '10705834' API_KEY = 'DMR1xQmxm8qpvQzfRFGuO2PI' SECRET_KEY = '2jB85tT2uCbNBrd6MBNFawBIaAaKqwG6' """ 读取图片 """ def get_file_content(filePath): with open(filePath, 'rb') as fp: return fp.read() """ 根据图片路径转文字 """ def get_texts(filePath): client = AipOcr(APP_ID, API_KEY, SECRET_KEY) image = get_file_content(filePath) texts=client.basicGeneral(image); result="" for item in texts["words_result"]: result+=item["words"] return result
3、common源码
#-*-coding:utf8-*- from datetime import * import time import random def randomcode(): nowTime = datetime.now().strftime("%Y%m%d%H%M%S")#生成当前的时间 randomNum = random.randint(0,100)#生成随机数n,其中0<=n<=100 if randomNum<=10: randomNum = str(0) + str(randomNum) uniqueNum = str(nowTime) + str(randomNum) return uniqueNum