C#とPythonでHTTP通信を行い、画像を受け渡すコードを記載します。
■C#側
public class RestClient
{
private static readonly string BASE_URL = "http://localhost:5000";
private HttpClient client = new HttpClient();
public RestClient()
{
}
public async Task<S> PostAsync<F, S>(F reqData)
{
string url = $"{BASE_URL}/api/data";
var requestData = reqData;
var jsonOptions = new JsonSerializerOptions
{
//WriteIndented = true
};
string jsonString = JsonSerializer.Serialize(requestData, jsonOptions);
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode == false)
{
return default(S);
}
string responseBody = await response.Content.ReadAsStringAsync();
S res = JsonSerializer.Deserialize<S>(responseBody, jsonOptions);
//Console.WriteLine(responseBody);
return res;
}
■コール部分
public class tModel
{
public string command { get; set; } = "";
public string img_b64 { get; set; } = "";
public string result { get; set; } = "";
}
private RestClient restClient = new RestClient();
private async void buttonCommTest_Click(object sender, EventArgs e)
{
Rectangle screenRect = Program.App.Param.Regions[0]; // 画面上の領域
using (Bitmap bmp = this.CaptureScreen(screenRect))
{
tModel req = new tModel();
req.img_b64 = Base64Encoder.EncodeBitmap(bmp); //画像をBase64文字列に変換
tModel res = await this.restClient.PostAsync<tModel, tModel>(req);
await Console.Out.WriteLineAsync(res.command);
using (Bitmap resImage = Base64Encoder.DecodeBitmap(res.img_b64))
{
//resImage.Show(this);
}
}
}
■Python側
from flask import Flask, jsonify, request
# POSTリクエストに対するルートエンドポイント
@app.route('/api/data', methods=['POST'])
def post_api_data():
request_data = request.get_json()
img_b64 = request_data['img_b64']
image : any = Base64Encoder.DecodeImage(img_b64)
#cv2.imwrite("target.png",image)
result : str = "";
# リクエストからデータを取得して処理する
response_data = request_data;
b64_str : str = Base64Encoder.EncodeImage(image)
response_data['img_b64'] = b64_str
response_data['result'] = result
#print(response_data)
return jsonify(response_data)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
これでC#とPython間で画像の受け渡しができます。
以上!
コメント