【问题标题】:send images through java android sockets通过 java android 套接字发送图像
【发布时间】:2021-06-09 21:52:09
【问题描述】:

我想通过套接字发送图像,但我无法在 android 中完成,有人可以帮我吗?

System.out.println("iniciooooo");

        //converting image to bytes with base64
        Bitmap b = BitmapFactory.decodeFile("/sdcard/ajeffer.jpg");
        ByteArrayOutputStream byte2= new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.JPEG,70,byte2);
        byte[] enbytes = byte2.toByteArray();
        String bb = Base64.encodeToString(enbytes,Base64.DEFAULT);
        System.out.println(Base64.encodeToString(enbytes,Base64.DEFAULT));
        data.writeUTF(bb);

        FileOutputStream file;

        //receiving the image in bytes to convert it into an image     
        DataInputStream dain = new DataInputStream(s.getInputStream());
        msg = dain.readUTF();
              
        File ff = new File("/sdcard/a2jeffer.jpg");
        byte[] deco = Base64.decode(dain.readUTF(),Base64.DEFAULT);
              
        Bitmap bit = BitmapFactory.decodeByteArray(deco,0,deco.length);
               
        file = new FileOutputStream(ff);
        bit.compress(Bitmap.CompressFormat.JPEG,70,file);
        //the image is not created

【问题讨论】:

  • 你不需要这一切。 writeUTF() 只能发送 64K 个字符,无论如何 Base-64 编码毫无意义。如果您确实必须进一步压缩,只需发送原始图像或压缩程度更高的图像的字节即可。您也不需要接收端的 BitmapFactory。两端只是标准的 Java 复制循环。
  • 我理解,我认为你是对的,我发现我必须从字符串中获取字节,但我没有设法将它保存为图像,你能给我一些例子吗代码如果不是太麻烦的话
  • 你不需要这个字符串。只需直接复制字节即可。这一切我都已经说了。

标签: java android sockets


【解决方案1】:

我意识到我的代码不起作用,因为我必须将这个 android: requestLegacyExternalStorage =" true " 放在清单中,而且我看到你对 writeUTF () 的看法是正确的,因为为了发送图像,我必须大幅降低质量但它可以工作如果您对如何改进这一点有任何想法,请告诉我,非常感谢。

【讨论】:

    【解决方案2】:

    你是对的,这对于发送和接收任何文件都很有效。

    发送文件

    OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = new FileInputStream(file);
            byte[] datita = new byte[16*1024];
            int count;
    
            while((count = inputStream.read(datita))>0){
                outputStream.write(datita,0,count);
            }
    
            outputStream.close();
            inputStream.close();
    

    接收文件

    OutputStream outputStream = new FileOutputStream(file);
                            InputStream inputStream = s.getInputStream();
                            byte[] datita = new byte[16*1024];
                            int count;
    
                            while((count = inputStream.read(datita))>0){
                                outputStream.write(datita,0,count);
                            }
                            outputStream.close();
                            inputStream.close();
    

    【讨论】:

      猜你喜欢
      • 2013-02-01
      • 2013-05-12
      • 2013-12-31
      • 2013-11-04
      • 2012-08-17
      • 2011-04-11
      • 1970-01-01
      相关资源
      最近更新 更多