我想通过套接字将图像从android设备发送到python,我已经成功地从android python发送了文本。 当我发送图像时,我会收到正在发送的图像,但在接收端,图像已损坏,大小为0 KB 我感谢任何帮助,因为我现在被困在这里
这是我的密码
image.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;
}
}
每次循环运行时,python代码都会截断输出文件。在最后一次运行时,当连接关闭时,文件被截断,
conn.recv
将返回一个空字符串,并且不会向文件写入任何其他内容将
with open(..)
移动到从套接字读取的循环之外,并处理连接关闭,这样就不会有无限循环:java代码在发送数据之前先发送它所发送的数据的大小——您应该删除它或调整python代码以考虑这一点
相关问题 更多 >
编程相关推荐