将字节数组转换为位图

时间:2017-03-20 20:10:13

标签: java android c++ image bitmap

我在cpp中有一个服务器,在Java中有一个客户端,我将服务器中的映像分段发送到客户端。在客户端,我选取所有段以形成单个字节数组。

我的问题是我似乎无法通过此字节数组成功创建位图,因为我使用BitmapFactory.decodeByteArray()

获取空值

客户代码:

byte[] response_bytes;
private Bitmap receive_image ( final String protocol, final int image_size, final int buffer_size)
{
    if (image_size <= 0 || buffer_size <= 0)
        return null;

    Thread image_receiver = new Thread(new Runnable() {
        @Override
        public void run() {
            ByteBuffer byteBuffer = ByteBuffer.allocate(image_size);
            byte[] buffer = new byte[buffer_size];
            int bytesReadSum = 0;
            try {
                while (bytesReadSum != image_size) {
                    activeReader.read(buffer);
                    String message = new String(buffer);
                    if (TextUtils.substring(message, 0, len_of_protocol_number).equals(protocol)) {
                        int bytesToRead = Integer.parseInt(TextUtils.substring(message, 
                                len_of_protocol_number, 
                                len_of_protocol_number + len_of_data_len));

                        byteBuffer.put(Arrays.copyOfRange(buffer, 
                                len_of_protocol_number + len_of_data_len, 
                                bytesToRead + len_of_protocol_number + len_of_data_len));
                        bytesReadSum += bytesToRead;
                    } else {
                        response_bytes = null;
                        break;
                    }
                }
                if (bytesReadSum == image_size) {
                    byte[] image_bytes = byteBuffer.array();
                    if (image_bytes.length > 0)
                        response_bytes = image_bytes;
                    else
                        response_bytes = null;
                }
            } catch (IOException e) {
                response_bytes = null;
            }
        }
    });
    image_receiver.start();
    try {
        image_receiver.join();
    } catch (InterruptedException e) {
        response_bytes = null;
    }

    if (response_bytes != null) {    //Here image_bitmap is null
        Bitmap image_bitmap = BitmapFactory.decodeByteArray(response_bytes, 0, response_bytes.length);
        return image_bitmap;
    } else {
        return null;
    }

此时我还想提一下,图像字节读取似乎工作正常,我设法读取图像的所有字节。 但是,我无法将该字节数组转换为位图。

0 个答案:

没有答案
相关问题