有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从Android到python的java图像传输socket问题

我正在尝试将图像从安卓客户端传输到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()

共 (1) 个答案

  1. # 1 楼答案

    您使用method将图像转换为字节,这使得您必须使用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
    

    我希望这有帮助