RuntimeException: Buffer not large enough for pixels

匿名 (未验证) 提交于 2019-12-03 02:27:02

问题:

I'm receiving a Bitmap in byte array through socket and I read it and then I want to set it os.toByteArray as ImageView in my application. The code I use is:

try {     //bmp = BitmapFactory.decodeByteArray(result, 0, 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 that ImageView is changed, it's not.

LogCat says:

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

I searched in similar questions but couldn't find a solution to my problem.

回答1:

Take a look at the source (version 2.3.4_r1, last time Bitmap was updated on Grepcode prior to 4.4) for Bitmap::copyPixelsFromBuffer()

The wording of the error is a bit unclear, but the code clarifies-- it means that your buffer is calculated as not having enough data to fill the pixels of your bitmap. This is (possibly) because they use the buffer's remaining() method to figure the capacity of the buffer, which takes into account the current value of its position attribute. If you call rewind() on your buffer before you invoke copyFromPixels(), you might see the runtime exception disappear. I say 'might' because the ByteBuffer::wrap() method should set the position attribute value to zero, removing the need to call rewind, but judging by similar questions and my own experience resetting the position explicitly may do the trick.

Try

ByteBuffer buffer = ByteBuffer.wrap(os.toByteArray()); buffer.rewind(); bitmap_tmp.copyPixelsFromBuffer(buffer); 


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