Flask-SocketIO send images
Asked Answered
P

3

7

I am currently working on a project that uses Flask-SocketIO to send things over the internet, but I came across this question.

Question:

Is there any way to send images in Flask-SocketIO? I did some googling but no luck for me.

Ptolemaist answered 20/11, 2018 at 19:11 Comment(0)
H
18

Socket.IO is a data agnostic protocol, so you can send any kind of information. Both text and binary payloads are supported.

If you want to send an image from the server, you can do something like this:

with open('my_image_file.jpg', 'rb') as f:
    image_data = f.read()
emit('my-image-event', {'image_data': image_data})

The client will have to be aware that you are sending jpeg data, there is nothing in the Socket.IO protocol that makes sending images different than sending text or other data formats.

If you are using a JavaScript client, you will get the data as a byte array. Other clients may choose the most appropriate binary representation for this data.

Harijan answered 23/11, 2018 at 9:29 Comment(3)
Worth noting this is for python3 and there's some different behavior for python2 as per github.com/miguelgrinberg/Flask-SocketIO/issues/195Arlyne
This answer got me very far! is f.read() still a good idea for files approaching 1GB? Or would it be better to process it in chunks, and have the file recomputed on the client's side? I'm learning a lot from this post!Bushmaster
f.read is only acceptable for small files. For large files you want to use streaming/chunking.Harijan
J
1

Adding to the accepted answer, I had a problem converting the ArrayBuffer in JavaScript to a jpeg image. I used the code inspired from [https://gist.github.com/candycode/f18ae1767b2b0aba568e][1]:

function receive_data(data) {
            

            var arrayBufferView = new Uint8Array(data['image']);
            var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );

            var img_url = URL.createObjectURL(blob);
            document.getElementById("fig_image").src = img_url;

        }
Janaye answered 13/9, 2021 at 15:27 Comment(0)
B
1

Additionally, I had to increase the max_http_buffer_size of the server like this:

from flask import Flask
from flask_socketio import SocketIO

app = Flask(__name__)

MAX_BUFFER_SIZE = 50 * 1000 * 1000  # 50 MB
socketio = SocketIO(app, max_http_buffer_size=MAX_BUFFER_SIZE)

Default is 1 MB.

Brassy answered 12/7, 2022 at 19:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.