Skip to content

Instantly share code, notes, and snippets.

@ilomon10
Created February 27, 2020 05:52
Show Gist options
  • Save ilomon10/ad86ac4ccd6fcb2925a57593438a366b to your computer and use it in GitHub Desktop.
Save ilomon10/ad86ac4ccd6fcb2925a57593438a366b to your computer and use it in GitHub Desktop.
Send image as base64 buffer from client (python opencv) to server (nodejs) using SocketIO
import cv2
import socketio #python-socketio by @miguelgrinberg
import base64
sio = socketio.Client()
sio.connect('http://x.x.x.x:xxxx)
cam = cv2.VideoCapture(0)
while (True):
ret, frame = cam.read() # get frame from webcam
res, frame = cv2.imencode('.jpg', frame) # from image to binary buffer
data = base64.b64encode(frame) # convert to base64 format
sio.emit('data', data) # send to server
cam.release()
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var sizeof = require('object-sizeof');
app.get('/', function (req, res) {
res.send('running');
})
io.on('connection', function (socket) {
socket.on('data', function (data) { // listen on client emit 'data'
var ret = Object.assign({}, data, {
frame: Buffer.from(data.frame, 'base64').toString() // from buffer to base64 string
})
io.emit('data', ret); // emmit to socket
})
})
http.listen(3000, function () {
console.log('listening on *:3333');
})
@paul2048
Copy link

Thanks! This is the only way I could send an image to the client through sockets.

@sadimoodi
Copy link

@paul2048 @ilomon10 i can not get the code to work, my node js server does not recieve the image, i tested with a string it worked but not with an image, i am using excatly the same code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment