【问题标题】:Sending an image file from an Android phone to a PC through Python using sockets使用套接字通过 Python 将图像文件从 Android 手机发送到 PC
【发布时间】: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


    【解决方案1】:

    您的 Python 代码会在每次循环运行时截断输出文件。在最后一次运行时,当连接关闭时,文件被截断,conn.recv 将返回一个空字符串,并且不会向文件中写入任何其他内容。

    with open(..) 移到从套接字读取的循环之外,并处理连接关闭,这样就不会出现无限循环:

    with open('image.jpg', 'wb') as file:
        while True:
            data = conn.recv(1024)
            if not data: break
            file.write(data)
    

    您的 java 代码在数据本身之前发送了它发送的数据的大小 - 您应该删除它或调整 python 代码以考虑到这一点。

                dataOutputStream.writeInt(voids[0].length);
                dataOutputStream.write(voids[0],0,voids[0].length);
    

    【讨论】:

    • 感谢您的回复,我已经按照您所说的进行了尝试,现在我得到了 3 KB 大小的图像,但是当我尝试打开图像时,它显示不支持文件格式和android 端我已经尝试将图像 android 发送到另一个 android 设备它工作正常。
    • 我也尝试过stackoverflow.com/questions/23312468/… 解决方案,但我收到错误为“TypeError: can only concatenate str (not "bytes") to str"
    • 你还在把图片数据的长度写入socket,写入文件吗?这将使您可以用来打开文件的任何文件格式都无法识别。另外,比较文件的确切大小(以字节为单位),“或多或少 3kb”不足以检测问题
    • 我没有在代码中提到任何大小,图像数据的大小是通过 voids[0].length 计算的
    • 所以你删除了这行代码? dataOutputStream.writeInt(voids[0].length)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多