【问题标题】:Sending image from android to PC via bluetooth通过蓝牙将图像从android发送到PC
【发布时间】:2012-10-09 09:53:50
【问题描述】:

我正在制作一个应用程序,用于将图像从 android 设备发送到在 PC 上运行的 java 应用程序。客户端(android)上的图像是Bitmap,我将其转换为Byte Array,以便通过蓝牙将其发送到服务器。

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

请注意,位图来自一个已经压缩的文件,所以我不需要再次压缩它。

我在服务器(Java)上使用以下代码:

  byte[] buffer = new byte[1024*1024];
  int bytes;
  bytes = inputStream.read(buffer);
  ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
  BufferedImage image = ImageIO.read(bais);
  ImageIO.write(image, "jpg", new File("c:/users/image.jpg"));

客户端没有错误。但是我在服务器端(java应用程序)得到了这个异常:

java.lang.IllegalArgumentException: im == null!

在 javax.imageio.ImageIO.write(Unknown Source)

在 javax.imageio.ImageIO.write(Unknown Source)

在 com.luugiathuy.apps.remotebluetooth.ProcessConnectionThread.run(ProcessConnectionThread.java:68)

在 java.lang.Thread.run(未知来源)

所以ImageIO.read() 没有返回任何东西。似乎它无法将字节数组识别为图像。我在互联网上搜索过,但没有任何东西可以帮助我解决这个问题。有人知道吗?

非常感谢!!

【问题讨论】:

  • java.lang.IllegalArgumentException: im == null!在 javax.imageio.ImageIO.write(Unknown Source) 在 javax.imageio.ImageIO.write(Unknown Source) 在 com.luugiathuy.apps.remotebluetooth.ProcessConnectionThread.run(ProcessConnectionThread.java:68) 在 java.lang.Thread。运行(未知来源)
  • 编辑您的问题并发布您的整个 logcat,以便社区成员可以帮助您,而不仅仅是部分内容

标签: java android bluetooth


【解决方案1】:

我终于明白了!碰巧客户端(Android)创建了一个用于接收的线程和一个用于写入的线程。所以,当我发送图像时,它是以块的形式发送的,即。 e.写入线程时不时地被 Android 操作系统暂停,所以服务器端(Java 应用程序)上的 inputStream 看到的是图像是碎片化的。所以,ImageIO.read() 没有成功读取图像,而是其中的一部分,这就是为什么我得到“java.lang.IllegalArgumentException:im == null!”,因为不能只用一个块创建图像。

解决方案:

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

安卓客户端:

    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();

希望它对某人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多