load Image From Assets - Android android.graphics

Android examples for android.graphics:Image Load Save

Description

load Image From Assets

Demo Code

import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Main {

  private static final int THUMBNAIL_SIZE = 1024;

  /**//from   ww  w  . ja  v  a2s . c o m
   * Loads given image asset, scaling the image down if it is too big to improve
   * performance.
   * 
   * @param context
   *          Application context
   * @param path
   *          Path in the assets folder of the image to load
   * @return Loaded image bitmap
   */
  public static Bitmap loadImageFromAssets(Context context, String path) {
    try {
      InputStream is = context.getAssets().open(path);

      BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
      onlyBoundsOptions.inJustDecodeBounds = true;
      onlyBoundsOptions.inDither = true;
      BitmapFactory.decodeStream(is, null, onlyBoundsOptions);
      is.close();

      if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) {
        return null;
      }

      int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight
          : onlyBoundsOptions.outWidth;

      double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE) : 1.0;
      int sampleSize = Integer.highestOneBit((int) Math.floor(ratio));

      BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
      bitmapOptions.inSampleSize = sampleSize;
      bitmapOptions.inDither = true;
      is = context.getAssets().open(path);
      Bitmap bitmap = BitmapFactory.decodeStream(is, null, bitmapOptions);
      is.close();

      return bitmap;
    } catch (IOException e) {
      return null;
    }
  }

}

Related Tutorials