如何从 android 发送 PNG 文件并在 python 中接收它

How to send PNG file from android and receive it in python

我正在尝试将 PNG 文件从我的 android 服务器发送到我的 python 客户端。
我尝试发送的 PNG 图片是截图,大约 4mb 大小,通常在 2mb 以下。

android代码(发送):

                File myFile = new File(imagePath);
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                Log.i("service", "sending file len");
                try {
                    out.write("" +myFile.length());
                    out.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.i("service:", "waiteing for ok");
                try {
                    msg = in.readLine();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.i("service", "sending file");
                byte[] outBuffer = new byte[(int) myFile.length()];
                try {
                    bis.read(outBuffer, 0, outBuffer.length);
                    os = client.getOutputStream();
                    os.write(outBuffer, 0, outBuffer.length);
                } catch (IOException e) {
                    e.printStackTrace();
                }

python代码(接收):

    print "waiting for responce's length"
    MSGLEN = int(sock.recv(bufferLen))
    print MSGLEN
    sock.sendall("ok" +"\n")

    chunks = []
    bytes_recd = 0
    while bytes_recd < MSGLEN:
        chunk = sock.recv(min(MSGLEN - bytes_recd, bufferLen))
        chunks.append(chunk)
        bytes_recd = bytes_recd + len(chunk)

    dataRecived = ''.join(chunks)
    print 'data receieved'
    print 'writing data to file'

    fileout = open("D:\shots.png", 'w')
    fileout.write(dataRecived)
    fileout.close()

文件从 android 传输到我的 PC,但文件已损坏。
当我将其与原始图像进行比较时,几乎所有内容都相同
除了这里和那里的一些空行(没有丢失信息,只是像有人添加的空行 \n)和 1 或 2 大块行(15 行左右)丢失。
Here 您可以看到文件之间的比较(左边是原始文件,右边是发送后的文件)。
我不知道为什么文件传输损坏,请帮助我。

尝试将其编码为 Base64 并发送一个简单的字符串。那些缺失的线也是图像数据的一部分 - 请记住它们是二进制的。

Base64 或 Bytestream 是你需要的