所以这就是我想要做的:有这个图像服务器将在端口 5003 上发送数据它将传输的数据格式如下 1 字节的图像类型(0=raw,1=JPEG)然后下一个 4 字节用于图像大小,然后将有 n 字节,其顺序如下:宽度 2 字节,高度 2 字节,B 1 字节,R 1 字节,G 1 字节
所以我要做的是获取数据并使用以下代码将其转换为图像:
#! /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`
但是每次我运行代码时总是会出现这种错误
"Value error not enough Image Data"
如果改变
img = Image.fromstring('RGB', (1280, 720), imageData, 'raw')
至
img = Image.fromstring('BRG', (1280, 720), imageData, 'raw')
我收到此错误:
Value error: Unrecognized mode,
任何人都知道如何解决这种问题?