将一堆图像从Android手机发送到PC

时间:2018-06-14 19:48:51

标签: java c# android image client-server

我正在开发一个应用程序,假设将图像从Android手机传输到服务器中的PC - 客户端架构(下面添加了java(android)代码)。这些照片假设通过bytearray。我很难弄清楚如何通过TCP创建一个能够传递我的图像而不会丢失信息的协议,并且能够传递图像的META-DATA,如图像名称,扩展名,大小,也许META-DATA大小(如果需要?)。我真的很感激你 帮助因为我对C#不熟悉并编写了一个客户端服务器,尤其是那些想要传输某种扩展图像的服务器。

private void makeTCPConnection() {
        try {
            InetAddress serverAddr = InetAddress.getByName("10.0.2.2");
            //create a socket to make the connection with the server
            Socket socket = new Socket(serverAddr, 8000);

            try {
                //Sends the message to the server
                OutputStream output = socket.getOutputStream();
                File dcim = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                if(dcim == null)
                    return;
                File[] pics=dcim.listFiles();
                int count=0;
                if(pics != null){
                    for(File pic:pics){

                    FileInputStream fis = new FileInputStream(pic);
                    Bitmap bm = BitmapFactory.decodeStream(fis);
                    byte[] imgbyte = getBytesFromBitmap(bm);
                    output.write(imgbyte);
                    output.flush();
                    }
                }
            }catch (Exception e){
             Log.e("TCP","S:Error",e);
            }finally {
                socket.close();
            }
        }catch (Exception e){
            Log.e("TCP","C:Error",e);
        }
    }

    public byte[] getBytesFromBitmap(Bitmap bitmap){
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG,70,stream);
        return stream.toByteArray();
    }

1 个答案:

答案 0 :(得分:0)

您是否考虑过写一个小REST web service

这种方法有一些优点:

  • HTTP(人类可读)用作协议,因此您不必提出自己的协议。
  • JSON(人类可读)可用于传输数据。 (可能不是照片,而是元数据。)
  • 客户端和服务器端有很多库。
  • 客户端和服务器可以用不同的语言编写。
  • 在某些语言中,只需几行代码即可创建REST Web服务。
  • 在编写客户端应用程序之前,可以先编写REST Web服务,然后对其进行测试(使用REST客户端)。
  • 可以轻松添加更多REST端点。 (也许你先建立一个简单的上传,然后再添加更多的端点来上传元数据。)

对于Android,我可以推荐Retrofit作为REST客户端。如果你想在服务器端使用Java,我建议你Spring/Spring Boot。 (如何在Spring Boot中指导REST Web服务:https://spring.io/guides/gs/rest-service/