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.
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.
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.
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;
}
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.
© 2022 - 2024 — McMap. All rights reserved.