Example usage for android.graphics BitmapFactory decodeStream

List of usage examples for android.graphics BitmapFactory decodeStream

Introduction

In this page you can find the example usage for android.graphics BitmapFactory decodeStream.

Prototype

@Nullable
public static Bitmap decodeStream(@Nullable InputStream is, @Nullable Rect outPadding, @Nullable Options opts) 

Source Link

Document

Decode an input stream into a bitmap.

Usage

From source file:Main.java

public static Bitmap decode(InputStream in, int reqWidth, int reqHeight) throws IOException {
    BufferedInputStream inputStream = new BufferedInputStream(in);
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;//w w w .j a  v  a 2s  . com
    inputStream.mark(64 * 1024);
    BitmapFactory.decodeStream(inputStream, null, options);
    inputStream.reset();
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeStream(inputStream, null, options);
}

From source file:Main.java

/**
 * <pre>//from   w  w  w  .j  a  va 2  s.c  o  m
 * Get width and height of bitmap from file.
 * </pre>
 * @param path path to file
 * @return integer array with 2 elements: width and height
 */
public static int[] getBitmapSizes(String path) throws IOException {
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    FileInputStream is = new FileInputStream(path);
    BitmapFactory.decodeStream(is, null, bmOptions);
    is.close();
    return new int[] { bmOptions.outWidth, bmOptions.outHeight };
}

From source file:Main.java

public static final int findScaleFactor(int targetW, int targetH, InputStream is) {
    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(is, null, bmOptions);
    int actualW = bmOptions.outWidth;
    int actualH = bmOptions.outHeight;

    // Determine how much to scale down the image
    return Math.min(actualW / targetW, actualH / targetH);
}

From source file:Main.java

/**resource methods*/

public static Bitmap getBitmap(Context context, String url) {
    Bitmap bitmap = null;/*from w w  w . j  av  a 2  s  . com*/
    InputStream is = null;
    try {
        url = url.trim();
        if (url.indexOf("res://") == 0) {
            int sepPos = url.lastIndexOf("/");
            int resId = context.getResources().getIdentifier(url.substring(sepPos + 1),
                    url.substring(6, sepPos), context.getPackageName());
            is = context.getResources().openRawResource(resId);
        } else if (url.indexOf("file://") == 0) {
            File file = new File(url.substring(7));
            if (file.canRead())
                is = new FileInputStream(file);
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inDither = true;
        bitmap = BitmapFactory.decodeStream(is, new Rect(), options);
        return bitmap;
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}

From source file:Main.java

/**
 * Loads given image asset, scaling the image down if it is too big to improve performance.
 * @param context Application context/*  www  .j  a  v  a2  s . co  m*/
 * @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 {
        // Open the input stream to the image in assets
        InputStream is = context.getAssets().open(path);

        // Load the image dimensions first so that big images can be scaled down (improves memory usage)
        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)) {
            // There was an error while decoding
            return null;
        }

        // Find the bigger dimension (width, height)
        int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth)
                ? onlyBoundsOptions.outHeight
                : onlyBoundsOptions.outWidth;

        // Calculate the sampling ratio for images that are bigger than the thumbnail size
        double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE) : 1.0;
        int sampleSize = Integer.highestOneBit((int) Math.floor(ratio));

        // Load the image sampled using the calculated 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;
    }
}

From source file:Main.java

/**
 * Decodes image from inputstream into a new Bitmap of specified dimensions.
 *
 * This is a long-running operation that must run in a background thread.
 *
 * @param is InputStream containing the image.
 * @param maxWidth target width of the output Bitmap.
 * @param maxHeight target height of the output Bitmap.
 * @return new Bitmap containing the image.
 * @throws IOException/* ww  w  . j ava2s.c om*/
 */
public static Bitmap decodeBitmapBounded(InputStream is, int maxWidth, int maxHeight) throws IOException {
    BufferedInputStream bufferedInputStream = new BufferedInputStream(is, STREAM_BUFFER_SIZE);
    try {
        bufferedInputStream.mark(STREAM_BUFFER_SIZE); // should be enough to read image dimensions.

        // TODO(mattfrazier): fail more gracefully if mark isn't supported, but it should always be
        // by bufferedinputstream.

        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(bufferedInputStream, null, bmOptions);
        bufferedInputStream.reset();

        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = calculateInSampleSize(bmOptions.outWidth, bmOptions.outHeight, maxWidth,
                maxHeight);

        // TODO(mattfrazier): Samsung devices yield a rotated bitmap no matter what orientation is
        // captured. Read Exif data and rotate in place or communicate Exif data and rotate display
        // with matrix.
        return BitmapFactory.decodeStream(bufferedInputStream, null, bmOptions);
    } finally {
        bufferedInputStream.close();
    }
}

From source file:Main.java

private static Bitmap readRoughScaledBitmap(InputStream is, float maxRatio) {
    Bitmap result;/* w w w  .ja  v a 2s  .c  om*/
    // Create the bitmap from file
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = (int) maxRatio;
    result = BitmapFactory.decodeStream(is, null, options);
    if (result != null) {
        Log.i("Photo Editor", "Read Scaled Bitmap Result wtf: " + result.getWidth() + " " + result.getHeight());
        Log.i("Photo Editor", "MaxRatio wtf: " + maxRatio);
    }
    return result;
}

From source file:Main.java

/**
 * Download the avatar image from the server.
 *
 * @param avatarUrl the URL pointing to the avatar image
 * @return a byte array with the raw JPEG avatar image
 */// w  w  w  .  j  a  va2  s . c  o  m
public static byte[] downloadAvatar(final String avatarUrl) {
    // If there is no avatar, we're done
    if (TextUtils.isEmpty(avatarUrl)) {
        return null;
    }

    try {
        Log.i(TAG, "Downloading avatar: " + avatarUrl);
        // Request the avatar image from the server, and create a bitmap
        // object from the stream we get back.
        URL url = new URL(avatarUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        try {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            final Bitmap avatar = BitmapFactory.decodeStream(connection.getInputStream(), null, options);

            // Take the image we received from the server, whatever format it
            // happens to be in, and convert it to a JPEG image. Note: we're
            // not resizing the avatar - we assume that the image we get from
            // the server is a reasonable size...
            Log.i(TAG, "Converting avatar to JPEG");
            ByteArrayOutputStream convertStream = new ByteArrayOutputStream(
                    avatar.getWidth() * avatar.getHeight() * 4);
            avatar.compress(Bitmap.CompressFormat.JPEG, 95, convertStream);
            convertStream.flush();
            convertStream.close();
            // On pre-Honeycomb systems, it's important to call recycle on bitmaps
            avatar.recycle();
            return convertStream.toByteArray();
        } finally {
            connection.disconnect();
        }
    } catch (MalformedURLException muex) {
        // A bad URL - nothing we can really do about it here...
        Log.e(TAG, "Malformed avatar URL: " + avatarUrl);
    } catch (IOException ioex) {
        // If we're unable to download the avatar, it's a bummer but not the
        // end of the world. We'll try to get it next time we sync.
        Log.e(TAG, "Failed to download user avatar: " + avatarUrl);
    }
    return null;
}

From source file:Main.java

public static Bitmap load(File file, int minSideLen, int maxSize) throws IOException {

    FileInputStream is = null;/*from  w ww  .  j  a v  a  2s.  c  om*/
    try {
        Options opts = new Options();
        opts.inJustDecodeBounds = true;

        is = new FileInputStream(file);
        BitmapFactory.decodeStream(is, null, opts);
        is.close();

        is = new FileInputStream(file);
        return load(is, computeSampleSize(opts, minSideLen, maxSize));
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:Main.java

/**
 * This is only used when the launcher shortcut is created.
 * //from w  w  w.  ja  v a2  s .c  o  m
 * @param bitmap The artist, album, genre, or playlist image that's going to
 *            be cropped.
 * @param size The new size.
 * @return A {@link Bitmap} that has been resized and cropped for a launcher
 *         shortcut.
 */
public static final Bitmap resizeAndCropCenter(final Bitmap bitmap, final int size) {
    Bitmap blurbitmap = null;

    final int w = bitmap.getWidth();
    final int h = bitmap.getHeight();
    if (w == size && h == size) {
        return bitmap;
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
    byte[] bitmapdata = bos.toByteArray();
    ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);

    try {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 8;
        options.inJustDecodeBounds = true;
        blurbitmap = BitmapFactory.decodeStream(bs, null, options);
        options.inJustDecodeBounds = false;

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bs != null) {
            try {
                bs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    final float mScale = (float) size / Math.min(w, h);

    final Bitmap mTarget = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
    final int mWidth = Math.round(mScale * blurbitmap.getWidth());
    final int mHeight = Math.round(mScale * blurbitmap.getHeight());
    final Canvas mCanvas = new Canvas(mTarget);
    mCanvas.translate((size - mWidth) / 2f, (size - mHeight) / 2f);
    mCanvas.scale(mScale, mScale);
    final Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG);
    mCanvas.drawBitmap(bitmap, 0, 0, paint);
    return mTarget;

}