Java – runtimeException: the buffer is insufficient to hold pixels

I received a bitmap in the byte array through the socket, I read it, and then I want to set it to OS. In my application Tobytearray as ImageView The code I use is:

try {
    //bmp = BitmapFactory.decodeByteArray(result,result.length);
    bitmap_tmp = Bitmap.createBitmap(540,719,Bitmap.Config.ARGB_8888);
    ByteBuffer buffer = ByteBuffer.wrap(os.toByteArray());

    bitmap_tmp.copyPixelsFromBuffer(buffer);
    Log.d("Server",result+"Length:"+result.length);
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            imageView.setImageBitmap(bitmap_tmp);
        }
    });
    return bmp;
} finally {
}

When I run my application and start receiving byte [] and expect the ImageView to be changed, it is not

Logcat said:

java.lang.RuntimeException: Buffer not large enough for pixels at
android.graphics.Bitmap.copyPixelsFromBuffer

I searched for similar problems, but I couldn't find a solution

Solution

For bitmap:: copypixelsfrombuffer(), please check the source (version 2.3.4_r1, last updated on grepcode before 4.4)

The wording of the error is a little unclear, but the code is clear - this means that your buffer calculates that there is not enough data to fill the pixels of the bitmap This is (possible) because they use the buffer's remaining () method to calculate the buffer's capacity, which takes into account the current value of its position attribute If rewind() is called in the buffer before calling copyfrompixels(), you may see the runtime exception disappear I said 'possible' because the ByteBuffer:: wrap () method should set the value of the position attribute to zero and there is no need to call rewind. However, judging from similar problems, my own experience may be helpful to explicitly reset the position

attempt

ByteBuffer buffer = ByteBuffer.wrap(os.toByteArray());
buffer.rewind();
bitmap_tmp.copyPixelsFromBuffer(buffer);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>