android 接收到的包含位图的字节数组返回空值

mznpcxlj  于 2023-01-07  发布在  Android
关注(0)|答案(1)|浏览(118)

我一直在尝试使用Google的BluetoothChat示例将图像从一个设备发送到另一个设备。我可以在设备之间发送字符串值,但在发送图像时遇到问题。我有两个类处理数据的接收和发送。
为了发送图像,我将图像路径转换为位图,然后将其转换为byte []并将其传递给实用程序类,与BluetoothChat示例相同,但增加了缓冲区大小(默认值为1024,将其更改为8192)。

send.setOnClickListener(view -> {
            Bitmap bitmap = BitmapFactory.decodeFile(filePath);

            int width = bitmap.getRowBytes();
            int height = bitmap.getHeight();
            int bmpSize = width * height;

            ByteBuffer byteBuffer = ByteBuffer.allocate(bmpSize);
            bitmap.copyPixelsToBuffer(byteBuffer);

            byte[] byteArray = byteBuffer.array();
            sendUtils.write(byteArray);

            bitmap.recycle();
    });

这是处理数据发送和接收的实用程序类,

/**
 * This thread runs during a connection with a remote device.
 * It handles all incoming and outgoing transmissions.
 */
private class ConnectedThread extends Thread {
    private final BluetoothSocket bluetoothsocket;
    private final InputStream inputStream;
    private final OutputStream outputStream;

    public ConnectedThread(BluetoothSocket socket) {
        bluetoothsocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        try {
            tmpIn = bluetoothsocket.getInputStream();
            tmpOut = bluetoothsocket.getOutputStream();
        } catch (IOException e) {
            Log.e("ConnectedThrd->Cons", "Socket not created.");
            e.printStackTrace();
        }
        inputStream = tmpIn;
        outputStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[8192]; //1024 original
        int bytes;

        // Keep listening to the InputStream while connected
        while (true) {
            try {
                // Read from the InputStream
                try {
                    bytes = inputStream.read(buffer);
                    // Send the obtained bytes to the UI Activity
                    handler.obtainMessage(BluetoothSend.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
                    handler.obtainMessage(BluetoothReceive.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
                } catch (NullPointerException n) {
                    Log.e("ConnectedThrd->Run", n.getMessage());
                }
            } catch (IOException e) {
                Log.e("ConnectedThrd->Run", "Connection Lost.", e);
                e.printStackTrace();
                connectionLost();
                break;
            }
        }
    }

    public void write(byte[] buffer) {
        try {
            try {
                outputStream.write(buffer);
                handler.obtainMessage(BluetoothSend.MESSAGE_WRITE, -1, -1, buffer)
                        .sendToTarget();
                handler.obtainMessage(BluetoothReceive.MESSAGE_WRITE, -1, -1, buffer)
                        .sendToTarget();
            } catch (NullPointerException n) {
                Log.e("ConnectedThrd->Write", "Bluetooth Socket is null: " + n.getMessage());
            }
        } catch (IOException e) {
            Log.e("ConnectedThread->Write", "Empty write stream.");
        }
    }

    public void cancel() {
        try {
            bluetoothsocket.close();
        } catch (IOException e) {
            Log.e("ConnectedThread->Cancel", "Failed to close socket.");
        }
    }
}

最后,在BluetoothReceive类中,我使用一个处理程序接收数据。处理程序对象的代码如下所示,

case MESSAGE_READ:
                //Read message from sender
                byte[] bufferRead = (byte[]) message.obj;
                //bitmap decodedByte is null
                Bitmap decodedByte = BitmapFactory.decodeByteArray(bufferRead, 0, bufferRead.length);
                int height = decodedByte.getHeight();
                int width = decodedByte.getWidth();

                Bitmap.Config config = Bitmap.Config.valueOf(decodedByte.getConfig().name());
                Bitmap bitmap_tmp = Bitmap.createBitmap(width, height, config);
                ByteBuffer buffer = ByteBuffer.wrap(bufferRead);
                bitmap_tmp.copyPixelsFromBuffer(buffer);
                fileView.setImageBitmap(bitmap_tmp);
                break;

当我尝试转换从另一个设备接收的字节数组时,我似乎总是得到一个空值,当我将它转换为位图,以便我可以使用它在ImageView中显示它时。
我哪里做错了?

carvr3hs

carvr3hs1#

正如你所说,你可以传递字符串,你可以把位图转换成Base64字符串格式并发送出去。

Bitmap bitmap = BitmapFactory.decodeFile("filePath");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
byte[] bytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(bytes, Base64.DEFAULT);

在接收端,将其反转(字符串Base64到图像)

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

相关问题