2012-08-31 32 views
3

我得到的錯誤是我的緩衝區對像素來說不夠大。任何建議?位圖b應該與gSaveBitmap大小相同,我試圖將其像素放入。緩衝區對於像素來說不夠大

if(gBuffer == null) 
     { 
      Bitmap b = Bitmap.createScaledBitmap(gBitmap, mWidth, mHeight, false); 
      //gBuffer = ByteBuffer.allocateDirect(b.getRowBytes()*b.getHeight()*4); 
      ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
      b.compress(Bitmap.CompressFormat.PNG, 100, stream); 
      gBuffer = ByteBuffer.wrap(stream.toByteArray()); 
      b.recycle(); 
     } 
     gSaveBitmap.copyPixelsFromBuffer(gBuffer); 

更新:下面的代碼給出了完全相同的錯誤,沒有涉及任何壓縮。

if(gBuffer == null) 
     { 
      Bitmap b = Bitmap.createScaledBitmap(gBitmap, mWidth, mHeight, false); 

      int bytes = b.getWidth()*b.getHeight()*4; 
      gBuffer = ByteBuffer.allocate(bytes); 
      b.copyPixelsToBuffer(gBuffer);    
      b.recycle(); 
     } 
     gSaveBitmap.copyPixelsFromBuffer(gBuffer); 

更新:通過加倍gBuffer的大小解決了這個問題。也許有人可以告訴我爲什麼這是正確的大小。另外...圖片旋轉錯誤,需要旋轉90度。任何想法如何在gBuffer中重新排列數據?

gBuffer = ByteBuffer.allocate(b.getRowBytes()*b.getHeight()*2); 
+0

png格式有4個通道(RGBA)通常,你可能會想東西的數據爲3通道位(RGB),這將使這個錯誤 –

+0

斯爾詹,不會JPEG CompressFormat修復程序問題,因爲它的24位RGB值? – lostdev

+0

其實,如果你只是複製一張圖片,爲什麼不使用像gSaveBitmap = b.copy(Bitmap.Config.ARGB_8888,true)之類的東西,而不是使用緩衝區/流? –

回答

1

我想我可能已經解決了這個one--看看源(版本2.3.4_r1,最後一次是位圖之前的4.4更新Grepcode)爲Bitmap::copyPixelsFromBuffer()

public void copyPixelsFromBuffer(Buffer src) { 

    checkRecycled("copyPixelsFromBuffer called on recycled bitmap"); 

    int elements = src.remaining(); 
    int shift; 
    if (src instanceof ByteBuffer) { 

     shift = 0; 

    } else if (src instanceof ShortBuffer) { 
     shift = 1; 

    } else if (src instanceof IntBuffer) { 
     shift = 2; 

    } else { 

     throw new RuntimeException("unsupported Buffer subclass"); 

    } 

    long bufferBytes = (long)elements << shift; 
    long bitmapBytes = (long)getRowBytes() * getHeight(); 

    if (bufferBytes < bitmapBytes) { 

     throw new RuntimeException("Buffer not large enough for pixels"); 

    } 

    nativeCopyPixelsFromBuffer(mNativeBitmap, src); 

} 

的錯誤的措辭有點不清楚,但代碼澄清 - 這意味着您的緩衝區計算爲沒有足夠的數據來填充位圖的像素。 這是因爲它們使用緩衝區的remaining()方法來計算緩衝區的容量,該緩衝區考慮了其位置屬性的當前值。如果在調用copyPixelsFromBuffer()之前調用緩衝區上的rewind(),則應該看到運行時異常消失。

0

我發現這個問題的答案:

你應該始終將buffer size > bit map size,因爲在不同的Android版本的位圖總是改變。

您可以登錄下面的代碼看buffer size & bitmap size(Android的API應該> = 12使用下面的日誌)

Log.i("", "Bitmap size = " + mBitmap.getByteCount()); 
     Log.i("", "Buffer size = " + mBuffer.capacity()); 

應該工作。

感謝,