記事一覧

createBitmap and recycle()

I wrote a code like this to get a shrunk image, but when I try to use the bitmapB in the following part I get "bitmap already recycled" error.


Matrix matrix = new Matrix()
matrix.postScale(0.5, 0.5);
Bitmap bitmapA = BitmapFactory.decodeResource(getResources(),anId);
Bitmap bitmapB = Bitmap.createBitmap( bitmapA, 0, 0, bitmapA.getWidth(), bitmapB.getHeight(),matrix, true);
bitmapA.recycle();

I wondered why and searched a bit to found this:
http://stackoverflow.com/questions/4648926/create-a-subset-of-bitmap-without-make-a-copy

I thought createBitmap() makes copy of the original bitmap but if the bitmap is immutable they(source and destination) share the same byte array on the memory.

I think it's pretty confusing to have "create" in the name of the method...

画像を縮小しようと思ってこんなコードを書いたのだけど、得られた bitmapB をこの後使おうとすると「recycle済みのビットマップを使用した」という旨のエラーが出ます。


Matrix matrix = new Matrix()
matrix.postScale(0.5, 0.5);
Bitmap bitmapA = BitmapFactory.decodeResource(getResources(),anId);
Bitmap bitmapB = Bitmap.createBitmap( bitmapA, 0, 0, bitmapA.getWidth(), bitmapB.getHeight(),matrix, true);
bitmapA.recycle();

なんでや? と思って調べてみたらこれが出てきました。
http://stackoverflow.com/questions/4648926/create-a-subset-of-bitmap-without-make-a-copy

createBitmap()ってビットマップをコピーして新たにビットマップを作るものかと思ってたんですが、元のビットマップが immutable の場合、同じバイト列を共有するようです。なので bitmapB を破棄してしまうと bitmapA も実体がなくなってしまう、と。

それは理解したとして、それってcreateBitmapっていう名前のイメージと違う・・・。混乱のもとですわ。