/**
* 將圖片轉換成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);
}