在 Python 中使用套接字编程接收图像 [英] Receive Image using socket programming in Python

查看:33
本文介绍了在 Python 中使用套接字编程接收图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to receive an image in python to use it in my program.

这是服务器代码:

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)

现在应该读取接收到的信息才能使用它.我是这样打开的:

The received should now be read to be able to use it. I am opening it like this:

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

但是当我在 cmd 中运行这两个代码时,输​​出是:收到以下数据 - + path 打开文件 - + path然后没有任何反应,尽管应该使用图像并且应该显示最终输出.

but when I run both codes in cmd the output is: The following data was received - + path Opening file - + path Then nothing happens although the image should be used and the final output should be shown.

有人可以帮忙吗?

推荐答案

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

I don't know if this is your (only) problem, but when working with binary files, you should pass the b flag to the built-in function open:

img = open(data, 'rb')

这篇关于在 Python 中使用套接字编程接收图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆