decode Sampled Bitmap From Stream - Android Graphics

Android examples for Graphics:Bitmap Stream

Description

decode Sampled Bitmap From Stream

Demo Code


import java.io.BufferedInputStream;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Main {

  public static final long KB_IN_BYTES = 1024;
  /**/*from ww w  . j  av  a2s . c o  m*/
   * Buffer is large enough to rewind past any EXIF headers.
   */
  private static final int THUMBNAIL_BUFFER_SIZE = (int) (128 * KB_IN_BYTES);

  public static Bitmap decodeSampledBitmapFromStream(InputStream stream, int reqWidth, int reqHeight) {
    Bitmap bitmap;
    try {
      InputStream inputStream = new BufferedInputStream(stream, THUMBNAIL_BUFFER_SIZE);
      inputStream.mark(THUMBNAIL_BUFFER_SIZE);

      final BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      options.inPreferredConfig = Bitmap.Config.RGB_565;
      BitmapFactory.decodeStream(inputStream, null, options);

      final int widthSample = options.outWidth / reqWidth;
      final int heightSample = options.outHeight / reqHeight;

      options.inJustDecodeBounds = false;
      options.inSampleSize = Math.min(widthSample, heightSample);

      inputStream.reset();
      bitmap = BitmapFactory.decodeStream(inputStream, null, options);
    } catch (Throwable ignored) {
      bitmap = null;
    }
    return bitmap;
  }
}

Related Tutorials