通过 Volley 多部分请求将捕获的图像手机发送到本地主机烧瓶服务器;接收 java.net.socketexcept



我正在尝试制作一个Android应用程序,该应用程序将通过手机捕获的图像发送到在flask上运行的本地主机服务器。我试图保持图像质量,因为我将在后端进行一些图像处理,这就是我使用 Volley 多部分请求的原因。但是当我将位图的 base64 编码字符串作为一个参数发送时,我从套接字收到错误,因为 java.net.socketexception 损坏了管道。

我已经尝试减小图像的大小,我也尝试仅发送字符串"hi"来代替编码的位图。当我这样做时,我得到了类似"E/Volley: [80295] BasicNetwork.performRequest: 意外响应代码 500"的响应。

 public byte[] getFileDataFromDrawable(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 50, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }
    private void uploadBitmap(final Bitmap bitmap) {
        final String tags = "image";
        String url="http://192.168.43.36:5000/recog";
        VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, url,
                new Response.Listener<NetworkResponse>() {
                    @Override
                    public void onResponse(NetworkResponse response) {
                        try {
                            JSONObject obj = new JSONObject(new String(response.data));
                            Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_LONG).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                String imgString = Base64.encodeToString(getFileDataFromDrawable(bitmap),
                        Base64.NO_WRAP);
                params.put("content", imgString);
//                params.put("content","hi");
                return params;
            }

//            @Override
//            protected Map<String, byte[]> getByteData() {
//                Map<String, byte[]> params = new HashMap<>();
//                params.put("content", getFileDataFromDrawable(bitmap));
//                return params;
//            }
        };

        Volley.newRequestQueue(this).add(volleyMultipartRequest);
    }

我在烧瓶文件中使用的代码如下:-

@app.route("/recog", methods=["POST"])
def get_face():
    json1= request.get_json()
    s=json1['content']
    return jsonify(message="Done")

我希望 base64 在烧瓶文件中解码并作为图像存储在本地设备上。

当您按照打印你有什么?。它是一系列base64编码的字符串

在 python 2.7 中

import base64
@app.route("/recog", methods=["POST"])
def get_face():
    json1= request.get_json()
    s=json1['content']
    fh = open("imageToSave.png", "wb")
    fh.write(s.decode('base64'))
    fh.close()
    return jsonify(message="Done")

或者你可以试试

import base64
@app.route("/recog", methods=["POST"])
def get_face():
    json1= request.get_json()
    s=json1['content']
    with open("imageToSave.png", "wb") as fh:
         fh.write(s.decode('base64'))
    return jsonify(message="Done")

对于Python 2.7和Python 3.x,您也可以尝试

import base64
with open("imageToSave.png", "wb") as fh:
     fh.write(base64.decodebytes(s))

或者你可以试试

with open("imageToSave.png", "wb") as fh:
     fh.write(base64.decodebytes(s.encode()))

请记住:始终检查代码以避免出现缩进错误消息

伙计们,我已经解决了这个问题。出现此问题是因为我尝试访问客户端通过 request.get_json(( 发送的表单/多部分数据,这是错误的。相反,我使用werkzeug.datastructures将数据转换为字典并访问所需的部分。

我目前在烧瓶中的代码如下:

from werkzeug.datastructures import ImmutableMultiDict
@app.route("/recog", methods=["POST"])
def get_face():
    data = dict(request.form)
    img=data['content']
    imgdata = base64.b64decode(img)
    filename = 'some_image.jpg'  
    with open(filename, 'wb') as f:
      f.write(imgdata)
    return jsonify(message="Done")

最新更新