通过套接字发送图像文件,安卓到Python

0 投票
2 回答
4248 浏览
提问于 2025-04-16 09:08

我正在尝试从一个安卓客户端向一个Python服务器发送图片,以前我用Python测试客户端和服务器成功过。简单来说,我的客户端应用会有一个表单,里面包含用户的详细信息和一张图片。当用户选择了图片后,我会在onActivityResult方法中获取到这个图片的URI,并把它转成字符串,像这样:

selectedImagePath = selectedImageUri.toString();

当用户点击表单上的提交按钮时,发送活动会被调用,表单数据会作为额外信息放在一个数组里,像这样:

Bundle b=new Bundle(); b.putStringArray("regValues", new String[]{name,email,selectedImagePath});

在发送活动中,我会和服务器建立连接,然后尝试发送图片,像这样:

` //建立与服务器的连接

    try{

     //refer to the host computer's loopback interface
     host = InetAddress.getByName("10.0.2.2"); 
     link = new Socket(host,port);
     in = new BufferedReader(new InputStreamReader(link.getInputStream()));

     //access the strings that were passed to this activity 
     Bundle b = this.getIntent().getExtras();
     String[] regFormValues = b.getStringArray("regValues");

     //display connection confirmation

     String message = in.readLine();
     status.setText(message);



        File myFile = new File (regFormValues[2]);
        byte [] mybytearray  = new byte [(int)myFile.length()];
        FileInputStream fis = new FileInputStream(myFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(mybytearray,0,mybytearray.length);
        OutputStream os = link.getOutputStream();

        os.write(mybytearray,0,mybytearray.length);
        os.flush();
        link.close();





    }
    catch(IOException e ){

     e.printStackTrace();

    }
    `

连接服务器没有问题,服务器也会像往常一样创建一个文件来写入数据,但这个文件看起来是空的,说明没有接收到数据。我觉得可能是客户端那边的文件路径有问题。你有什么想法吗?

补充:基本上我想知道我是否以正确的方式访问图片文件,或者你有没有更好的建议来访问和发送它。

2 个回答

0

可以考虑使用一些方法,比如 File.exists() 和 File.isFile(),来检查路径是否正确,以及图片是否真的存在。

还可以检查一下图片是否真的被发送出去,可以用 tcpdump 或者 wireshark 这些工具。

0

我解决了这个问题,方法是:如果照片是用相机拍的,我用 selectedImageUri = Uri.fromFile(photo); 来获取它的地址;如果是从文件浏览器中选择的照片,我就用 selectedImageUri = data.getData();。然后,我用 selectedImagePath = selectedImagePath.substring(7); 来去掉相机照片路径中的 "file://" 部分,这样就得到了类似于 /sdcard/etc 的路径,或者是它存储的其他地方。对于从文件浏览器选择的图片,我使用了这个方法:

// convert the image URI to the direct file system path of the image file  
public String getRealPathFromURI(Uri contentUri) {  

    // can post image  
    String [] proj={MediaStore.Images.Media.DATA};  
    Cursor cursor = managedQuery( contentUri,  
            proj, // Which columns to return  
            null,       // WHERE clause; which rows to return (all rows)  
            null,       // WHERE clause selection arguments (none)  
            null); // Order-by clause (ascending by name)  
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
    cursor.moveToFirst();  

    return cursor.getString(column_index);  

现在一切都按预期工作了。

撰写回答