您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

通过蓝牙将图像从android发送到PC

通过蓝牙将图像从android发送到PC

我终于可以弄清楚了!碰巧,客户端(Android)创建了一个用于接收的线程和一个用于写入的线程。因此,当我发送图像时,它是成块发送的,即Android OS会不时暂停写入线程,因此服务器端(Java应用程序)上的inputStream看到图像是成块的。因此,ImageIO.read()不是成功读取图像而是读取图像的一部分,这就是为什么我得到“ java.lang.IllegalArgumentException:im == null!”的原因,因为仅凭一个块就无法创建任何图像。

除了图像之外,我还向服务器发送了“文件结束”字符串,因此它知道文件何时完成(我想对此有更好的方法,但这是可行的)。在服务器端,在while循环中,我接收所有字节块并将它们全部放在一起,直到接收到“文件末尾”。代码

Android客户端:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);     
    byte[] b = baos.toByteArray();
    mBluetoothService.write(b);
    mBluetoothService.write("end of file".getBytes());

Java服务器:

    byte[] buffer = new byte[1024];

    File f = new File("c:/users/temp.jpg");
    FileOutputStream fos = new FileOutputStream (f);

    int bytes = 0;
    boolean eof = false;

    while (!eof) {

        bytes = inputStream.read(buffer);
        int offset = bytes - 11;
        byte[] eofByte = new byte[11];
        eofByte = Arrays.copyOfRange(buffer, offset, bytes);
        String message = new String(eofByte, 0, 11);

        if(message.equals("end of file")) {

            eof = true;

        } else {

            fos.write (buffer, 0, bytes);

        }

    }
    fos.close();

希望它能帮助到别人。

其他 2022/1/1 18:32:05 有520人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶