Read bitmap from byte array and calculate its sample size - Android android.graphics

Android examples for android.graphics:Bitmap Load Save

Description

Read bitmap from byte array and calculate its sample size

Demo Code


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

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;

public class Main {
  /**/*w  w w .j  a v a  2  s.c o  m*/
   * Read bitmap for the purpose of vehicle
   * 
   * @param data
   * @return
   */
  public static Bitmap readBitmapVehicle(byte[] data) {
    Bitmap tempBmp = null;
    Options tempBmpOptions = null;

    try {
      InputStream is = new ByteArrayInputStream(data);
      tempBmpOptions = new BitmapFactory.Options();
      tempBmpOptions.inJustDecodeBounds = true;
      tempBmpOptions.inPreferredConfig = Config.ARGB_8888;
      tempBmp = BitmapFactory.decodeStream(is, null, tempBmpOptions);
      tempBmpOptions.inSampleSize = calculateInSampleSize(tempBmpOptions, 80,
          80);
      tempBmpOptions.inJustDecodeBounds = false;
      tempBmpOptions.inBitmap = tempBmp;
      is.close();

      try {
        is = new ByteArrayInputStream(data);
        tempBmp = BitmapFactory.decodeStream(is, null, tempBmpOptions);
        is.close();
      } catch (IOException e1) {
        e1.printStackTrace();
      }

    } catch (IOException e1) {
      e1.printStackTrace();
    }

    return tempBmp;
  }

  public static int calculateInSampleSize(BitmapFactory.Options options,
      int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

      final int halfHeight = height / 2;
      final int halfWidth = width / 2;

      // Calculate the largest inSampleSize value that is a power of 2 and
      // keeps both
      // height and width larger than the requested height and width.
      while ((halfHeight / inSampleSize) > reqHeight
          && (halfWidth / inSampleSize) > reqWidth) {
        inSampleSize *= 2;
      }
    }

    return inSampleSize;
  }
}

Related Tutorials