使用python套接字发送图像,图像brocken

时间:2016-08-27 11:35:38

标签: python image sockets

我想创建一个客户端,它将图像和字符串列表发送到服务器。 首先,我想把eerything放在一个List中,然后用pickle创建一个字符串,这样我就可以发送它了。 但不幸的是,这个字符串变得很大,以便处理pickle,所以我只使用了两个插槽,一个用于列表,一个用于图像。

它奏效了,但我收到的图像已经破了。

这是原始图片:

enter image description here

这是复制的图像:

enter image description here

正如您所看到的,底部不存在,但真正的问题是,我无法在我的kivy应用中使用该图像,而原始图像可以正常工作。 我该如何解决这个问题?

这是服务器:

import socket
import errno
import base64
import pickle

from PIL import Image
import StringIO

def connect(c):#recursive funktion, that deals with the errorno 11
    try:
        strings = c.recv(8192)
        return strings
    except IOError as e:
        if e.errno == errno.EWOULDBLOCK:
            connect(c)


def Main():
    host = IP
    port = 12345

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
    s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    s.bind((host, port))
    s.listen(5)


    while True:

        c, addr = s.accept()


        print "Connection from: " + str(addr)

        strings = connect(c)

        #gets the image
        c.send('give image')
        #c.flush()
        c.close()

        c, addr = s.accept()
        image = connect(c)
        imgname = 'test.png'

        if image == 'cusdom_image':
            with open('images.png', "rb") as imageFile:
                image = ''
                image = base64.b64encode(imageFile.read())
                print image
        fh = open(imgname, "wb")
        fh.write(image.decode('base64'))
        fh.close()


if __name__ == '__main__':
    Main()

这是客户:

import socket
import base64
import pickle

from PIL import Image
import StringIO
import os, sys

ip = '138.106.181.133'
port = 12345
print 'Add event executed'
s = socket.socket()#makes socket for the first time
s.connect((ip, port))

image_path = '/home/gilgamesch/PTTT/icon.png'

print os.getcwd()
olddir = os.getcwd()
os.chdir('/')
print os.getcwd()

new_list = ['Some', 'random', 'string', 'list', ]
new_compact_list = pickle.dumps(new_list)
s.send(new_compact_list)

recived = s.recv(1023)

if image_path != '':
    with open(image_path, "rb") as imageFile:
        image_data = base64.b64encode(imageFile.read())
        print 'open worked'
else:
    image_data = 'cusdom_image'

os.chdir(olddir)

if recived == 'give image':
    s.close()
    s = socket.socket()#remakes socket to send image
    s.connect((ip, port))
    s.sendall(image_data)


s.close()

顺便说一句,bitcode很好,当客户端读取它时,我测试它,它被破坏,当它被发送到服务器时。

0 个答案:

没有答案