使用Python中的套接字编程接收图像

时间:2013-06-07 17:49:30

标签: python sockets tcp

我正在尝试在python中接收图像以在我的程序中使用它。

这是服务器代码:

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("127.0.0.1", 5005))
server_socket.listen(5)

data = ' ' 
client_socket, address = server_socket.accept()
print "Conencted to - ",address,"\n"
while (1):
    data = client_socket.recv(1024)
    print "The following data was received - ",data
    print "Opening file - ",data
    img = open(data,'r')
    while True:
      strng = img.readline(512)
      if not strng:
        break
      client_socket.send(strng)
      img.close()
      print "Data sent successfully"
      exit()
      #data = 'viewnior '+data
      #os.system(data)

这是客户端代码:

import socket,os
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("127.0.0.1", 5005))
size = 1024

while(1):
    print "Enter file name of the image with extentsion (example: filename.jpg,filename.png or if a video file then filename.mpg etc) - "
    fname = raw_input()
    client_socket.send(fname)
    #fname = 'documents/'+fname
    fp = open(fname,'w')
    while True:
        strng = client_socket.recv(512)
        if not strng:
            break
        fp.write(strng)
    fp.close()
    print "Data Received successfully"
    exit()
    #data = 'viewnior '+fname
    #os.system(data)

现在应该阅读收到的内容以便能够使用它。我打开它是这样的:

input_image = Image.open('data').convert('L').resize((100, 100))

但是当我在cmd中运行两个代码时,输​​出是: The following data was received - + path Opening file - + path 然后,虽然应该使用图像并且应该显示最终输出,但没有任何反应。

任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:1)

我不知道这是否是您的(唯一)问题,但在处理二进制文件时,您应该将b标记传递给内置函数open

img = open(data, 'rb')