/**
* 将图片转换成Base64编码的字符串
*/
public String bitmaptoString(Bitmap bitmap) {
// 将Bitmap转换成字符串
String string = null;
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 100, bStream);
byte[] bytes = bStream.toByteArray();
string = Base64.encodeToString(bytes, Base64.DEFAULT);
return string;
}
/**
* init engine
* call in onCreate
*
* @return
*/
private String onRunModel() {
try {
String assetImagePath="images/1.jpg";
InputStream imageStream = getAssets().open(assetImagePath);
Bitmap image = BitmapFactory.decodeStream(imageStream);
String params=bitmaptoString(image);
Log.d("params", "params_base64: "+params);
String strUrlPath = "http://192.168.2.44:8080/TestServer/" ;
URL url=new URL(strUrlPath);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
// httpURLConnection.setConnectTimeout(3000); //设置连接超时时间
httpURLConnection.setDoInput(true); //打开输入流,以便从服务器获取数据
httpURLConnection.setDoOutput(true); //打开输出流,以便向服务器提交数据
httpURLConnection.setRequestMethod("POST"); //设置以Post方式提交数据
httpURLConnection.setUseCaches(false); //使用Post方式不能使用缓存
//设置请求体的类型是文本类型
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.connect(); //连接即往服务端发送消息
DataOutputStream dop=new DataOutputStream(httpURLConnection.getOutputStream());
dop.writeBytes("data="+URLEncoder.encode(params,"utf-8"));
dop.flush();//清空缓存
dop.close();//关闭
//下面开始做接收工作
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String result="";
String readLine=null;
while((readLine=bufferedReader.readLine())!=null){
result+=readLine;
}
bufferedReader.close();
httpURLConnection.disconnect();
String strResult = URLDecoder.decode(result,"utf-8");
Log.d("strResult", "strResult: "+strResult);
try {
JSONObject json = new JSONObject(result);
JSONArray ReceiptLines=json.getJSONArray("ReceiptLines");
Log.d("ReceiptLines", "ReceiptLines: "+ReceiptLines);
return String.valueOf(ReceiptLines);
} catch (JSONException e) {
e.printStackTrace();
return "";
}
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
private void onRunModelSuccessed(String result) {
Log.i(TAG, "onRunModelSuccessed");
textView.setText(result); //输出结果
imageView.setImageBitmap(predictor.outputImage);
}