繁体   English   中英

使用套接字向Android发送图像文件到Python

[英]Send an image file using sockets , Android to Python

我试图将图像从android客户端发送到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();

    }
    `

它没有问题地连接到服务器,服务器创建了一个文件以供输出以照常写入数据,但是它看起来是空的,因此没有数据被接收。 我认为这可能与客户端上的文件路径有关。 有任何想法吗 ?

编辑:基本上我想知道我是否以正确的方式访问图像文件,或者您是否对访问和发送它有更好的建议。

考虑使用诸如File.exists()和File.isFile()之类的方法来验证路径是否正确以及图像是否确实存在

还要检查图像是否碰到电线-使用tcpdump ro wirehark

我已经解决了它,因为我use selectedImageUri = Uri.fromFile(photo); 获取uri(如果它是由相机拍摄的),并且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);  

现在它可以按预期工作了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM