简体   繁体   English

图片从Android传输到python套接字问题

[英]Image transferring from Android to python socket issue

I'm trying transfer image from android client to python server , but i have a problem , the image sent successfully but there are some change in size , the image received will be like : 我正在尝试将图像从android客户端传输到python服务器,但是我有一个问题,图像发送成功,但是尺寸有所变化,收到的图像将像:

Example

from size 6Mb to 60Kbyte! 从6Mb到60Kbyte!
my Java (client) look like this : 我的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();

and the server code Python : 和服务器代码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()

you convert images to bytes using method makes you have to compress them using bitmap.compress in this line : 您使用方法将图像转换为字节使得您必须在此行中使用bitmap.compress对其进行压缩

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

try to change this method to : 尝试将此方法更改为:

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

// ... etc

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM