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:com.ocp.media.UriTexture.java

public static final Bitmap createFromUri(Context context, String uri, int maxResolutionX, int maxResolutionY,
        long cacheId, ClientConnectionManager connectionManager)
        throws IOException, URISyntaxException, OutOfMemoryError {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = false;/*w ww .  j ava  2  s  .c o m*/
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    options.inDither = true;
    long crc64 = 0;
    Bitmap bitmap = null;
    if (uri.startsWith(ContentResolver.SCHEME_CONTENT)) {
        // We need the filepath for the given content uri
        crc64 = cacheId;
    } else {
        crc64 = Utils.Crc64Long(uri);
    }
    bitmap = createFromCache(crc64, maxResolutionX);
    if (bitmap != null) {
        return bitmap;
    }
    final boolean local = uri.startsWith(ContentResolver.SCHEME_CONTENT) || uri.startsWith("file://");

    // Get the input stream for computing the sample size.
    BufferedInputStream bufferedInput = null;
    if (uri.startsWith(ContentResolver.SCHEME_CONTENT) || uri.startsWith(ContentResolver.SCHEME_FILE)) {
        // Get the stream from a local file.
        bufferedInput = new BufferedInputStream(context.getContentResolver().openInputStream(Uri.parse(uri)),
                16384);
    } else {
        // Get the stream from a remote URL.
        bufferedInput = createInputStreamFromRemoteUrl(uri, connectionManager);
    }

    // Compute the sample size, i.e., not decoding real pixels.
    if (bufferedInput != null) {
        options.inSampleSize = computeSampleSize(bufferedInput, maxResolutionX, maxResolutionY);
    } else {
        return null;
    }

    // Get the input stream again for decoding it to a bitmap.
    bufferedInput = null;
    if (uri.startsWith(ContentResolver.SCHEME_CONTENT) || uri.startsWith(ContentResolver.SCHEME_FILE)) {
        // Get the stream from a local file.
        bufferedInput = new BufferedInputStream(context.getContentResolver().openInputStream(Uri.parse(uri)),
                16384);
    } else {
        // Get the stream from a remote URL.
        bufferedInput = createInputStreamFromRemoteUrl(uri, connectionManager);
    }

    // Decode bufferedInput to a bitmap.
    if (bufferedInput != null) {
        options.inDither = false;
        options.inJustDecodeBounds = false;
        Thread timeoutThread = new Thread("BitmapTimeoutThread") {
            public void run() {
                try {
                    Thread.sleep(6000);
                    options.requestCancelDecode();
                } catch (InterruptedException e) {
                }
            }
        };
        timeoutThread.start();

        bitmap = BitmapFactory.decodeStream(bufferedInput, null, options);
    }

    if ((options.inSampleSize > 1 || !local) && bitmap != null) {
        writeToCache(crc64, bitmap, maxResolutionX / options.inSampleSize);
    }
    return bitmap;
}

From source file:prince.app.sphotos.Gallery.UriTexture.java

public static final Bitmap createFromUri(Context context, String uri, int maxResolutionX, int maxResolutionY,
        long cacheId, ClientConnectionManager connectionManager)
        throws IOException, URISyntaxException, OutOfMemoryError {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = false;//  ww  w  . ja  v  a  2s .c o m
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    options.inDither = true;
    long crc64 = 0;
    Bitmap bitmap = null;
    if (uri.startsWith(ContentResolver.SCHEME_CONTENT)) {
        // We need the filepath for the given content uri
        crc64 = cacheId;
    } else {
        crc64 = Utils.Crc64Long(uri);
    }

    bitmap = createFromCache(crc64, maxResolutionX);
    if (bitmap != null) {
        Log.i(TAG, "!!! Bitmap in cache !!!");
        return bitmap;
    }

    final boolean local = uri.startsWith(ContentResolver.SCHEME_CONTENT) || uri.startsWith("file://");

    // Get the input stream for computing the sample size.
    BufferedInputStream bufferedInput = null;
    if (uri.startsWith(ContentResolver.SCHEME_CONTENT) || uri.startsWith(ContentResolver.SCHEME_FILE)) {
        // Get the stream from a local file.
        bufferedInput = new BufferedInputStream(context.getContentResolver().openInputStream(Uri.parse(uri)),
                16384);
    } else {
        // Get the stream from a remote URL.
        bufferedInput = createInputStreamFromRemoteUrl(uri, connectionManager);
    }

    // Compute the sample size, i.e., not decoding real pixels.
    if (bufferedInput != null) {
        options.inSampleSize = computeSampleSize(bufferedInput, maxResolutionX, maxResolutionY);
    } else {
        return null;
    }

    // Get the input stream again for decoding it to a bitmap.
    bufferedInput = null;
    if (uri.startsWith(ContentResolver.SCHEME_CONTENT) || uri.startsWith(ContentResolver.SCHEME_FILE)) {
        // Get the stream from a local file.
        bufferedInput = new BufferedInputStream(context.getContentResolver().openInputStream(Uri.parse(uri)),
                16384);
    } else {
        // Get the stream from a remote URL.
        bufferedInput = createInputStreamFromRemoteUrl(uri, connectionManager);
    }

    // Decode bufferedInput to a bitmap.
    if (bufferedInput != null) {
        options.inDither = false;
        options.inJustDecodeBounds = false;
        Thread timeoutThread = new Thread("BitmapTimeoutThread") {
            public void run() {
                try {
                    Thread.sleep(6000);
                    options.requestCancelDecode();
                } catch (InterruptedException e) {
                }
            }
        };
        timeoutThread.start();

        bitmap = BitmapFactory.decodeStream(bufferedInput, null, options);
    }

    if ((options.inSampleSize > 1 || !local) && bitmap != null) {
        //   writeToCache(crc64, bitmap, maxResolutionX / options.inSampleSize);
        writeToCache(crc64, bitmap, maxResolutionX);
    }
    return bitmap;
}

From source file:vn.mbm.phimp.me.gallery3d.media.UriTexture.java

public static final Bitmap createFromUri(Context context, String uri, int maxResolutionX, int maxResolutionY,
        long cacheId, ClientConnectionManager connectionManager)
        throws IOException, URISyntaxException, OutOfMemoryError {
    Log.i(TAG, "creatFromUri()");
    Log.i(TAG, "URI: " + uri);
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = false;//from www.  java  2s .  c o  m
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    options.inDither = true;
    long crc64 = 0;
    Bitmap bitmap = null;
    if (uri.startsWith(ContentResolver.SCHEME_CONTENT)) {
        // We need the filepath for the given content uri
        crc64 = cacheId;
    } else {
        crc64 = Utils.Crc64Long(uri);
    }
    bitmap = createFromCache(crc64, maxResolutionX);
    if (bitmap != null) {
        return bitmap;
    }
    final boolean local = uri.startsWith(ContentResolver.SCHEME_CONTENT) || uri.startsWith("file://");

    // Get the input stream for computing the sample size.
    BufferedInputStream bufferedInput = null;
    if (uri.startsWith(ContentResolver.SCHEME_CONTENT) || uri.startsWith(ContentResolver.SCHEME_FILE)) {
        // Get the stream from a local file.
        bufferedInput = new BufferedInputStream(context.getContentResolver().openInputStream(Uri.parse(uri)),
                16384);
    } else {
        // Get the stream from a remote URL.
        bufferedInput = createInputStreamFromRemoteUrl(uri, connectionManager);
    }

    // Compute the sample size, i.e., not decoding real pixels.
    if (bufferedInput != null) {
        options.inSampleSize = computeSampleSize(bufferedInput, maxResolutionX, maxResolutionY);
    } else {
        return null;
    }

    // Get the input stream again for decoding it to a bitmap.
    bufferedInput = null;
    if (uri.startsWith(ContentResolver.SCHEME_CONTENT) || uri.startsWith(ContentResolver.SCHEME_FILE)) {
        // Get the stream from a local file.
        bufferedInput = new BufferedInputStream(context.getContentResolver().openInputStream(Uri.parse(uri)),
                16384);
    } else {
        // Get the stream from a remote URL.
        bufferedInput = createInputStreamFromRemoteUrl(uri, connectionManager);
    }

    // Decode bufferedInput to a bitmap.
    if (bufferedInput != null) {
        options.inDither = false;
        options.inJustDecodeBounds = false;
        Thread timeoutThread = new Thread("BitmapTimeoutThread") {
            public void run() {
                try {
                    Thread.sleep(6000);
                    options.requestCancelDecode();
                } catch (InterruptedException e) {
                }
            }
        };
        timeoutThread.start();

        bitmap = BitmapFactory.decodeStream(bufferedInput, null, options);
    }

    if ((options.inSampleSize > 1 || !local) && bitmap != null) {
        writeToCache(crc64, bitmap, maxResolutionX / options.inSampleSize);
    }
    return bitmap;
}

From source file:edu.stanford.mobisocial.dungbeetle.ImageViewerActivity.java

@Override
public void onResume() {
    super.onResume();
    if (mIntent.hasExtra("image_url")) {
        String url = mIntent.getStringExtra("image_url");
        ((App) getApplication()).objectImages.lazyLoadImage(url.hashCode(), Uri.parse(url), im);
        bitmap = mgr.getBitmap(url.hashCode(), url);
    } else if (mIntent.hasExtra("b64Bytes")) {
        String b64Bytes = mIntent.getStringExtra("b64Bytes");
        ((App) getApplication()).objectImages.lazyLoadImage(b64Bytes.hashCode(), b64Bytes, im);
        bitmap = mgr.getBitmapB64(b64Bytes.hashCode(), b64Bytes);
    } else if (mIntent.hasExtra("bytes")) {
        byte[] bytes = mIntent.getByteArrayExtra("bytes");
        ((App) getApplication()).objectImages.lazyLoadImage(bytes.hashCode(), bytes, im);
        bitmap = mgr.getBitmap(bytes.hashCode(), bytes);
    } else if (mIntent.hasExtra("obj")) {
        try {/*from   w w  w .j ava  2s  .  co  m*/
            final JSONObject content = new JSONObject(mIntent.getStringExtra("obj"));
            byte[] bytes = FastBase64.decode(content.optString(PictureObj.DATA));
            ((App) getApplication()).objectImages.lazyLoadImage(bytes.hashCode(), bytes, im);
            bitmap = mgr.getBitmap(bytes.hashCode(), bytes);
        } catch (JSONException e) {
        }
    }

    if (mIntent.hasExtra("objHash")) {
        if (!ContentCorral.CONTENT_CORRAL_ENABLED) {
            return;
        }

        long objHash = mIntent.getLongExtra("objHash", -1);
        final DbObj obj = App.instance().getMusubi().objForHash(objHash);
        final JSONObject json = obj.getJson();
        if (json.has(CorralClient.OBJ_LOCAL_URI)) {
            // TODO: this is a proof-of-concept.
            new Thread() {
                public void run() {
                    try {
                        if (!mCorralClient.fileAvailableLocally(obj)) {
                            //toast("Trying to go HD...");
                        }
                        // Log.d(TAG, "Trying to go HD...");
                        final Uri fileUri = mCorralClient.fetchContent(obj);
                        if (fileUri == null) {
                            try {
                                Log.d(TAG, "Failed to go HD for " + json.getString(CorralClient.OBJ_LOCAL_URI));
                            } catch (JSONException e) {
                                Log.d(TAG, "Failed to go HD for " + json);
                            }
                            return;
                        }
                        // Log.d(TAG, "Opening HD file " + fileUri);

                        InputStream is = getContentResolver().openInputStream(fileUri);
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 4;

                        Matrix matrix = new Matrix();
                        float rotation = PhotoTaker.rotationForImage(ImageViewerActivity.this, fileUri);
                        if (rotation != 0f) {
                            matrix.preRotate(rotation);
                        }
                        bitmap = BitmapFactory.decodeStream(is, null, options);

                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                im.setImageBitmap(bitmap);
                            }
                        });
                    } catch (IOException e) {
                        // toast("Failed to go HD");
                        Log.e(TAG, "Failed to get hd content", e);
                        // continue
                    }
                };
            }.start();
        }
    }
}

From source file:playn.android.AndroidAssets.java

@Override
protected Image loadImage(String path, ImageReceiver<Bitmap> recv) {
    Exception error = null;//from ww w.  j  a v a 2  s  .  c o m
    for (Scale.ScaledResource rsrc : assetScale().getScaledResources(path)) {
        try {
            InputStream is = openAsset(rsrc.path);
            try {
                BitmapOptions options = createOptions(path, true, rsrc.scale);
                return recv.imageLoaded(BitmapFactory.decodeStream(is, null, options), options.scale);
            } finally {
                is.close();
            }
        } catch (FileNotFoundException fnfe) {
            error = fnfe; // keep going, checking for lower resolution images
        } catch (Exception e) {
            error = e;
            break; // the image was broken not missing, stop here
        }
    }
    platform.log().warn("Could not load image: " + pathPrefix + path, error);
    return recv.loadFailed(error != null ? error : new FileNotFoundException(path));
}

From source file:com.ridgelineapps.wallpaper.Utils.java

public static Bitmap computeBitmapSizeFromURI(Context context, Uri imageURI) throws FileNotFoundException {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;/*from   www . j  a  v a 2s  . c o  m*/

    // BitmapFactory.decodeStream(new FileInputStream(imageURI), null, options);
    // BitmapFactory.decodeStream(context.getContentResolver().openInputStream(imageURI), null, options);
    return BitmapFactory.decodeStream(context.getContentResolver().openInputStream(imageURI), null, options);
}

From source file:com.rightscale.app.dashboard.ShowServerMonitoring.java

public Bitmap produceImage(String tag) throws RestException {
    //TODO thread safety
    if (_selectedGraphUri == null) {
        return null;
    }//from  w  w  w . j  av a2s .  c om

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 1;

    try {
        Bitmap bitmap = null;
        InputStream in = null;
        in = openHttpConnection(_selectedGraphUri);
        bitmap = BitmapFactory.decodeStream(in, null, options);
        in.close();
        return bitmap;
    } catch (IOException e) {
        throw new RestException(e);
    }
}

From source file:com.ibuildapp.romanblack.CouponPlugin.CouponAdapter.java

/**
 * Decode rss item image thad storing in given file
 * @param imagePath - image file path/*from   w w  w  .ja v  a2  s .c  om*/
 * @return decoded image Bitmap
 */
private Bitmap decodeImageFile(String imagePath) {
    try {
        File file = new File(imagePath);
        //Decode image size
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(file), null, opts);

        //Find the correct scale value. It should be the power of 2.
        int width = opts.outWidth, height = opts.outHeight;
        int scale = 1;
        while (true) {
            if (width / 2 < imageWidth || height / 2 < imageHeight) {
                break;
            }
            width /= 2;
            height /= 2;
            scale *= 2;
        }

        //Decode with inSampleSize
        opts = new BitmapFactory.Options();
        opts.inSampleSize = scale;

        Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file), null, opts);

        int x = 0, y = 0, l = 0;
        if (width > height) {
            x = (int) (width - height) / 2;
            y = 0;
            l = height;
        } else {
            x = 0;
            y = (int) (height - width) / 2;
            l = width;
        }

        float matrixScale = (float) (imageWidth - 4) / (float) l;
        Matrix matrix = new Matrix();
        matrix.postScale(matrixScale, matrixScale);

        return Bitmap.createBitmap(bitmap, x, y, l, l, matrix, true);
    } catch (Exception e) {
    }

    return null;
}

From source file:com.nextgis.maplibui.util.ControlHelper.java

public static Bitmap getBitmap(InputStream is, BitmapFactory.Options options) {
    Bitmap result = null;/*  ww  w.j  a v a  2 s  .  c o  m*/
    if (is == null)
        return null;

    try {
        result = BitmapFactory.decodeStream(is, null, options);
    } catch (OutOfMemoryError oom) {
        oom.printStackTrace();

        try {
            options.inSampleSize *= 4;
            result = BitmapFactory.decodeStream(is, null, options);
        } catch (OutOfMemoryError oom1) {
            oom1.printStackTrace();
        }
    }

    try {
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}