[英]Image transferring from Android to python socket issue
我正在嘗試將圖像從android客戶端傳輸到python服務器,但是我有一個問題,圖像發送成功,但是尺寸有所變化,收到的圖像將像:
從6Mb到60Kbyte!
我的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()
您使用方法將圖像轉換為字節使得您必須在此行中使用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
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.