Sending image from android to PC via bluetooth

你说的曾经没有我的故事 提交于 2019-12-01 14:08:11

I could finally figure it out! It happens that the client (Android) creates a thread for receiving and a thread for writing. So, when I send an image, it's sent in chunks, i. e. the writing threads is paused every now and then by the Android OS, so what the inputStream on the server side (Java app) sees is that the image is coming in pieces. So, ImageIO.read() is not successfully reading an image but a piece of it, and that's why I'm getting the "java.lang.IllegalArgumentException: im == null!", cause no image can be created with just a chunk.

Solution:

Besides the image, I also send an "end of file" string to the server, so it knows when the file is complete (I suppose there are better ways to to this, but this is working). At the server side, in a while loop I receive all the byte chunks and put them all together until an "end of file" is received. The code:

Android client:

    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 server:

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

Hope it helps somebody.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!