从android到python的图像传输套接字问题

rkue9o1l  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(331)

我正在尝试将图像从android客户端传输到python服务器,但我遇到了一个问题,图像发送成功,但大小有一些变化,接收到的图像将如下所示:
例子
从6mb到60KB!
我的java(客户端)如下所示:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
byte[] array = bos.toByteArray();

OutputStream out = photoSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);

dos.writeInt(array.length);
dos.write(array);

dos.flush();
dos.close();

photoSocket.close();

服务器代码python:

import socket
import struct
address = ("xxx.xxx.x.x", 9200)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(address)
s.listen(1000)

client, addr = s.accept()
print('got connected from', addr)

buf = b''
while len(buf)<4:
buf += client.recv(4-len(buf))
size = struct.unpack('!i', buf)
print("receiving %s bytes" % size)

with open('tst.jpg', 'wb') as img:
    while True:
        data = client.recv(1024)
        if not data:
            break
        img.write(data)
print('received, yay!')

client.close()
ukdjmx9f

ukdjmx9f1#

使用方法将图像转换为字节使您必须使用 bitmap.compress 在此行中:

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);

尝试将此方法更改为:

int size = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
bitmap.copyPixelsToBuffer(byteBuffer);
byteArray = byteBuffer.array();

// ... etc

我希望这有帮助。

相关问题