Trevor
Trevor

Reputation: 1035

Proper Use of Android BitmapFactory.decodeByteArray

I have searched for some time now and I cannot find an example implementation for android's BitmapFactory.decodeByteArray()

I am looking to understand how function works as I am planning to use it for a project I am working on, but I haven't been able to get a simple example working. Here is the code I have:

public Bitmap createRandomBitmap() {
    int h = 300;
int w = 300;

buf = new byte[h * w * 4];

for (int i = 0; i < h * w * 4;i++) {
    buf[i] = 127;
}

bmp = BitmapFactory.decodeByteArray(buf, 0, h * w);
return bmp;
}

This always returns null, which according to the documentation means the bitmap failed to load. But I can't figure out why. This should be using the default ARGB_8888 format, where each pixel has 4 bytes. I thought I had taken care of that above. Any suggestions?

Upvotes: 1

Views: 1616

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007399

If you want to create a raw Bitmap the way you are, BitmapFactory is not the answer. Use setPixel() on Bitmap, or some flavor of the createBitmap() factory method on Bitmap, or create a Bitmap-backed Canvas and draw using Canvas operations.

BitmapFactory is for decoding bitmaps in recognized formats, such as PNG and JPEG.

Upvotes: 4

Related Questions