[PYTHON] Send and receive Flask images

Overview

There was not much Japanese processing for image transmission / reception processing, so I will summarize it.

Sample code

Here is a sample code for echoing back an image.

Send / receive


@app.route("/echo_back", methods=['POST'])
def test():
    img_bin = io.BytesIO(request.data).getvalue() #Receive
    response = make_response(img_bin) #Set the image in the response
    response.headers.set('Content-Type', request.content_type) #Header setting
    
    return response

The points are shown below. --Image information is stored in "request.data". If this is an io.ByteIO type, only image information can be acquired. Since it is echoed back this time, it is immediately converted to bytes type using getvalue (). --When storing image information in make_response (), it seems that it must be bytes type. Therefore, as mentioned above, getvalue () is used as bytes type. --Finally, "Content-type" is set in the header.

If you want to perform image processing on the way, convert the type as appropriate. If it is opencv, it will be a numpy array. In the case of PIL, should it be something like Image.open (io.BytesIO (request.data))?

Test method

I am using "POST MAN". This section describes the settings when "POST MAN" is used.

--Communication is "POST" (since only POST is allowed this time) --Add "Content-Type" to Header and set "Value" according to the file format of the image file --Set Body to "binary" and select an image file

Basically, use the above settings. This allows you to confirm that the file you sent will be returned as is.

Recommended Posts

Send and receive Flask images
[aws] Send and receive sqs messages
Send messages and images using LineNotify
POST variously with Python and receive with Flask
Start communication with UDP and send and receive with TCP
Send and receive Gmail via the Gmail API using Python
POST the image with json and receive it with flask
Install Python and Flask (Windows 10)
Send experiment results (text and images) to slack with Python
Extract and package initrd images
React and Flask to GCP
Send and receive data with MQTT via Watson IoT Platform
Basic authentication and Digest authentication with Flask
Login with PycURL and receive response
Upload and download images with falcon
Send and receive image data as JSON over the network with Python
Send and receive binary data via serial communication with python3 (on mac)