so here is what I'm trying to do: There is this image server that will send data on port 5003 The format of the data it will transmit is as follows 1 byte for the image type(0=raw, 1=JPEG) then the next 4 byte for the image size then after that there will be n byte with the following order 2 byte for width, 2 byte for height, 1 byte for B, 1 byte for R, 1 byte for G
So what I'm trying to do is to get the data and transform it into an image with the following code:
#! /usr/bin/python
import socket
import sys
import binascii
from PIL import Image
from StringIO import StringIO
# Connect to the server image
serverHost = 'localhost'
serverPort = 5003
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((serverHost, serverPort))
print >>sys.stderr, 'Connecting to host: ' + str(serverHost)
print >>sys.stderr, 'and server Port: ' + str(serverPort)
s.settimeout(1)
#Receive the image type
imageType = s.recv(1)
print>>sys.stderr, 'received %r' %binascii.hexlify(imageType)
print>>sys.stderr, 'Unpacked: ', int(binascii.hexlify(imageType), 16)
received = imageType.__len__()
print>> sys.stderr, "Received: ", received
#Receive the image size
imageSize = s.recv(4)
print>>sys.stderr, 'received %r' %binascii.hexlify(imageSize)
print>>sys.stderr, 'Unpacked: ', int(binascii.hexlify(imageSize), 16)
received = imageSize.__len__()
print>> sys.stderr, "Received: ", received
#Receive the image Data
imageData = ''
received =0
while(received < int(binascii.hexlify(imageSize), 16)):
buffer = s.recv(4096)
imageData += buffer
received += buffer.__len__()
print>> sys.stderr, "Received: ", received
img = Image.fromstring('RGB', (1280, 720), imageData, 'raw')
#img = Image.open(StringIO(binascii.hexlify(imageData)))
img = img.convert('RGB')
img.save('out.png')
#file = open('test.png', 'w');
#file.write(imageData)
#file.close()
#When we receive the image, we send the acknowledgement
s.send('OK')
s.close()`enter code here`
But everytime I run the code it always get this kind of error
"Value error not enough Image Data"
And if change
img = Image.fromstring('RGB', (1280, 720), imageData, 'raw')
to
img = Image.fromstring('BRG', (1280, 720), imageData, 'raw')
I get this error:
Value error: Unrecognized mode,
Anyone knows how to solve this kind of problem?
struct? Besides all this, the other possible source of error is the server, which was not presented by you. As a suggestion, you will also need to send the image mode, otherwise how are you going to know whether you have a 'L', 'RGB', and others, as the mode in your original jpg ?structmodule) you might need to call s.recv() multiple times i.e.,s.recv(4)may return less than 4 bytes (you could callf = s.makefile('rb'); f.read(4)to make sure either 4 bytes are read or EOF is encountered. Uselen(buff)instead ofbuff.__len__()