Android How to - Loads and creates a scaled bitmap by path / widhDp / heightDp








Question

We would like to know how to loads and creates a scaled bitmap by path / widhDp / heightDp.

Answer

import java.io.IOException;
/*  www  .  j  a v  a  2  s.  c  o  m*/
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Main {

  /**
   * Loads and creates a scaled bitmap by path / widhDp / heightDp
   * @param context The context
   * @param bitmapFilePath The file path of the bitmap data file
   * @param widthDp Width of the bitmap in Dp
   * @param heightDp Height of the bitmap in Dp
   * @return The scaled bitmap
   * @throws IOException If error occurs during bitmap data decoding
   */
  public static Bitmap loadScaledBitmap(Context context, String bitmapFilePath, int widthDp, int heightDp) throws IOException {
    
    //create movie icon
    Bitmap bitmap;
    //calculate dimensions in px   
    int movieIconWidthDp = 300;
    int movieIconHeightDp = 400;

    bitmap=BitmapFactory.decodeStream(context.openFileInput(bitmapFilePath));

    bitmap=Bitmap.createScaledBitmap(bitmap, movieIconWidthDp, movieIconHeightDp, true);
    return bitmap;
  }

}