从Android到python的图像传输

2024-04-29 07:30:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Example

从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()

Tags: 图像服务器client客户端newclosedatasocket
1条回答
网友
1楼 · 发布于 2024-04-29 07:30:31

将图像转换为字节的方法使您必须使用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

我希望这有帮助

相关问题 更多 >