【发布时间】:2020-07-17 11:00:31
【问题描述】:
我想通过套接字将图像从我的 android 设备发送到 python,我已经成功地从 Android-Python 发送文本。 当我发送图像时,我得到了正在发送的图像的吐司,但在接收端,图像已损坏,大小为 0 KB 我很感激任何帮助,因为我目前被困在这里。
这是我的代码
图像.py
from socket import *
port = 8888
s = socket(AF_INET, SOCK_STREAM)
s.bind(('', port))
s.listen(1) #listens to 1 connection
conn, addr = s.accept()
print("Connected by the ",addr)
while True:
data = conn.recv(1024)
with open('image.jpg', 'wb') as file:
file.write(data)
conn.close()
Android端代码是,
public void send(View v) {
Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(i, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imageView.setImageBitmap(selectedImage);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] array = byteArrayOutputStream.toByteArray();
SendImageClient sendImageClient = new SendImageClient();
sendImageClient.execute(array);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "no image selected", Toast.LENGTH_SHORT).show();
}
}
public class SendImageClient extends AsyncTask<byte[], Void, Void> {
@Override
protected Void doInBackground(byte[]... voids) {
try {
Socket socket= new Socket("192.168.0.106",8888);
OutputStream out=socket.getOutputStream();
DataOutputStream dataOutputStream=new DataOutputStream(out);
dataOutputStream.writeInt(voids[0].length);
dataOutputStream.write(voids[0],0,voids[0].length);
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "Image sent", Toast.LENGTH_SHORT).show();
}
});
dataOutputStream.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
【问题讨论】:
标签: java python android image sockets