Introduction

A bitmap is a digital image composed of a matrix of dots. When viewed at 100%, each dot corresponds to an individual pixel on a display. A bitmap can be acquired by loading a file, reading in a collection of bytes or even taking a photo from device camera.

Creating Bitmap

A bitmap is a rectangle of pixels. Each pixel can be set to a given color. To create a Bitmap

Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);

// Sets all of the pixels to the specified color, red in this case. 
b.eraseColor(Color.RED);

The first two parameters give the width and the height in pixels. The third parameter specifies the type of pixel. The specification ARGB_8888 means create a pixel with four channels ARGB – Alpha, Red, Green, Blue and allocate each 8 bits of storage. As four eights are 32 this is 32 bit graphics. The alpha channel lets you set an opacity. There are many different pixel formats you can select and there is always a trade off between the resolution and the amount of space a bitmap occupies.

Most of the methods of the Bitmap object are concerned with things that change the entire image. However using the setPixel and getPixel methods you can access any pixel and perform almost any graphics operation.

 

Displaying Bitmap

A bitmap can be displayed using ImageView. Below example shows how you can use the ImageView to display a Bitmap.

public class LoadImages extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Bitmap bMap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
    bMap.eraseColor(Color.RED);
 
    ImageView image = (ImageView) findViewById(R.id.test_image);
    image.setImageBitmap(bMap);
  }
}

 

Bitmap conversion

To get Bitmap from Drawables

ImageView image = (ImageView) findViewById(R.id.image);
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.car);
image.setImageBitmap(b);

To convert a Bitmap object into a Drawable

Drawable d = new BitmapDrawable(getResources(), bitmap);

 

Scaling a Bitmap

To resize a Bitmap, call createScaledBitmap()method to resize any bitmap to desired width and height.

public class LoadImages extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Bitmap bMap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
    bMap.eraseColor(Color.RED);

    // Resize the bitmap to 150x100 (width x height)
    Bitmap scaled = Bitmap.createScaledBitmap(bMap, 150, 100, true);
 
    ImageView image = (ImageView) findViewById(R.id.test_image);
    image.setImageBitmap(scaled);
  }
}