简体   繁体   中英

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 :

Example

from size 6Mb to 60Kbyte!
my Java (client) look like this :

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 :

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.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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