Creating a New Bitmap Instance
A fresh bitmap can be alloacted by specifying dimensions and a pixel configuration. Here, a mutable 24-bit RGB image without an alpha channel is generated:
int canvasWidth = 400;
int canvasHeight = 300;
Bitmap mutableBitmap = Bitmap.createBitmap(canvasWidth, canvasHeight, Bitmap.Config.RGB_565);
The RGB_565 config uses 16 bits per pixel, consuming less memory when transparency isn’t required.
Decoding an Image File
To load a drawable resource, decode it directly into a bitmap. The sample uses a raw resource identifier:
Bitmap loadedImage = BitmapFactory.decodeResource(getResources(), R.raw.sample_photo);
decodeResource resolves the resource, reads its data, and returns an immutable bitmap by default. For large images, prefer decoding with BitmapFactory.Options to downsample and avoid out-of-memory errors.
Attaching a Bitmap to an ImageView
Once the bitmap is ready, bind it to an ImageView for display:
ImageView previewView = findViewById(R.id.previewImageView);
previewView.setImageBitmap(loadedImage);
The UI thread renders the bitmap immediately. If the bitmap can be replaced later, remember to recycle the old one to release native memory.
Memory Management Considerations
Bitmaps hold significant native memory. Call bitmap.recycle() when the bitmap is no longer needed, and be cautious when retaining references in Activity or Fragment lifecycle callbacks. Consider using Bitmap.Config.ARGB_8888 only when translucency is necessary.