Example usage for android.graphics BitmapRegionDecoder decodeRegion

List of usage examples for android.graphics BitmapRegionDecoder decodeRegion

Introduction

In this page you can find the example usage for android.graphics BitmapRegionDecoder decodeRegion.

Prototype

public Bitmap decodeRegion(Rect rect, BitmapFactory.Options options) 

Source Link

Document

Decodes a rectangle region in the image specified by rect.

Usage

From source file:Main.java

public static void cropImage(File original, File output, Rect imageRect, Rect cropRect)
        throws FileNotFoundException, IOException {
    Point dimen = getImageDimensions(original);
    float scaledW = imageRect.right - imageRect.left;
    float scaledH = imageRect.bottom - imageRect.top;
    float scale = Math.min((float) dimen.x / scaledW, (float) dimen.y / scaledH);

    Rect cropRegion = getIntrinsicCropRegion(dimen, cropRect, scale);
    BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(original.getPath(), false);
    Bitmap bitmap = decoder.decodeRegion(cropRegion, null);
    saveBitmap(output, bitmap);/*  w ww. jav  a2  s.com*/
}

From source file:Main.java

public static Bitmap decodeByteArray(byte[] buffer, int reqWidth, int reqHeight) {
    BitmapFactory.Options opts = new BitmapFactory.Options();

    // Determine insample size
    opts.inJustDecodeBounds = true;/*from  www.  ja  va 2s . com*/
    BitmapFactory.decodeByteArray(buffer, 0, buffer.length, opts);
    opts.inSampleSize = calculateInSampleSize(opts, reqWidth, reqHeight);

    // Decode the bitmap, regionally if necessary
    Bitmap bitmap = null;
    opts.inJustDecodeBounds = false;
    Rect rect = getCropRectIfNecessary(opts, reqWidth, reqHeight);
    try {
        if (rect != null) {
            BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(buffer, 0, buffer.length, false);
            bitmap = decoder.decodeRegion(rect, opts);
        } else {
            bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length, opts);
        }
    } catch (IOException e) {
        Log.e(TAG, "Unable to decode bitmap from stream", e);
    }
    return bitmap;
}

From source file:Main.java

public static Bitmap decodeStream(InputStream is, int reqWidth, int reqHeight) {
    BitmapFactory.Options opts = new BitmapFactory.Options();

    // Determine insample size
    opts.inJustDecodeBounds = true;//w ww . j  a v a 2  s.  co m
    BitmapFactory.decodeStream(is, null, opts);
    opts.inSampleSize = calculateInSampleSize(opts, reqWidth, reqHeight);

    // Decode the bitmap, regionally if necessary
    Bitmap bitmap = null;
    opts.inJustDecodeBounds = false;
    Rect rect = getCropRectIfNecessary(opts, reqWidth, reqHeight);
    try {
        if (rect != null) {
            BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(is, false);
            bitmap = decoder.decodeRegion(rect, opts);
        } else {
            bitmap = BitmapFactory.decodeStream(is, null, opts);
        }
    } catch (IOException e) {
        Log.e(TAG, "Unable to decode bitmap from stream", e);
    }
    return bitmap;
}

From source file:Main.java

public static Bitmap decodeResource(Resources res, int resId, int reqWidth, int reqHeight) {
    BitmapFactory.Options opts = new BitmapFactory.Options();

    // Determine insample size
    opts.inJustDecodeBounds = true;//from  w ww. j  av a  2 s.  c  om
    BitmapFactory.decodeResource(res, resId, opts);
    opts.inSampleSize = calculateInSampleSize(opts, reqWidth, reqHeight);

    // Decode the bitmap, regionally if necessary
    Bitmap bitmap = null;
    opts.inJustDecodeBounds = false;
    Rect rect = getCropRectIfNecessary(opts, reqWidth, reqHeight);

    InputStream stream = null;
    try {
        if (rect != null) {
            stream = res.openRawResource(resId, new TypedValue());
            if (stream == null)
                return null;
            BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(stream, false);
            bitmap = decoder.decodeRegion(rect, opts);
        } else {
            bitmap = BitmapFactory.decodeResource(res, resId, opts);
        }
    } catch (IOException e) {
        Log.e(TAG, "Unable to open resource " + resId, e);
    } finally {
        closeSilently(stream);
    }
    return bitmap;
}

From source file:Main.java

private static Bitmap regionDecode(String path, int reqWidth, int reqHeight, int outWidth, int outHeight)
        throws IOException {
    BitmapRegionDecoder regionDecoder = BitmapRegionDecoder.newInstance(path, true);
    if (reqWidth > outWidth) {
        reqWidth = outWidth;//from  ww  w  . jav a2  s .  c  om
    }
    if (reqHeight > outHeight) {
        reqHeight = outHeight;
    }

    return regionDecoder.decodeRegion(new Rect(0, 0, reqWidth, reqHeight), null);
}

From source file:Main.java

@TargetApi(10)
private static Bitmap getSidebarWallpaperApi10(Context context, SharedPreferences preferences, int sidebarWidth,
        int sidebarHeight) {
    boolean useBackground = preferences.getBoolean("pref_sidebar_custom_background", false);
    if (!useBackground)
        return null;

    String path = preferences.getString("pref_sidebar_background_image", null);
    if (path == null)
        return null;

    try {//www  .  j  a v a 2  s  . c o  m
        BitmapFactory.Options bounds = decodeBounds(createWallpaperInputStream(context, path));
        int decodeHeight = Math.min(bounds.outHeight, sidebarHeight);
        int decodeWidth = Math.min(bounds.outWidth, sidebarWidth);
        InputStream in = createWallpaperInputStream(context, path);
        try {
            BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(in, false);
            BitmapFactory.Options options = new BitmapFactory.Options();
            return decoder.decodeRegion(new Rect(0, 0, decodeWidth, decodeHeight), options);
        } finally {
            in.close();
        }
    } catch (IOException e) {
        return null;
    }

}

From source file:com.aimfire.gallery.service.PhotoProcessor.java

private void saveThumbnail(String sbsPath, String thumbPath) {
    try {//from  ww  w  .j a  va  2 s . c om
        BitmapRegionDecoder decoder = null;
        Bitmap bmp = null;

        decoder = BitmapRegionDecoder.newInstance(sbsPath, false);
        bmp = decoder.decodeRegion(new Rect(0, 0, decoder.getWidth() / 2, decoder.getHeight()), null);

        Bitmap thumb = ThumbnailUtils.extractThumbnail(bmp, MainConsts.THUMBNAIL_SIZE,
                MainConsts.THUMBNAIL_SIZE);

        FileOutputStream fos;
        fos = new FileOutputStream(thumbPath);
        thumb.compress(CompressFormat.JPEG, 50, fos);
        fos.close();

        if (bmp != null) {
            bmp.recycle();
        }

        if (thumb != null) {
            thumb.recycle();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.facebook.imagepipeline.platform.DefaultDecoder.java

/**
 * Create a bitmap from an input stream.
 *
 * @param inputStream the InputStream//from   w w w  .  j  a v a2 s. c  o m
 * @param options the {@link android.graphics.BitmapFactory.Options} used to decode the stream
 * @param regionToDecode optional image region to decode or null to decode the whole image
 * @param transformToSRGB whether to allow color space transformation to sRGB at load time
 * @return the bitmap
 */
private CloseableReference<Bitmap> decodeFromStream(InputStream inputStream, BitmapFactory.Options options,
        @Nullable Rect regionToDecode, final boolean transformToSRGB) {
    Preconditions.checkNotNull(inputStream);
    int targetWidth = options.outWidth;
    int targetHeight = options.outHeight;
    if (regionToDecode != null) {
        targetWidth = regionToDecode.width() / options.inSampleSize;
        targetHeight = regionToDecode.height() / options.inSampleSize;
    }
    int sizeInBytes = getBitmapSize(targetWidth, targetHeight, options);
    final Bitmap bitmapToReuse = mBitmapPool.get(sizeInBytes);
    if (bitmapToReuse == null) {
        throw new NullPointerException("BitmapPool.get returned null");
    }
    options.inBitmap = bitmapToReuse;

    // Performs transformation at load time to sRGB.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && transformToSRGB) {
        options.inPreferredColorSpace = ColorSpace.get(ColorSpace.Named.SRGB);
    }

    Bitmap decodedBitmap = null;
    ByteBuffer byteBuffer = mDecodeBuffers.acquire();
    if (byteBuffer == null) {
        byteBuffer = ByteBuffer.allocate(DECODE_BUFFER_SIZE);
    }
    try {
        options.inTempStorage = byteBuffer.array();
        if (regionToDecode != null) {
            BitmapRegionDecoder bitmapRegionDecoder = null;
            try {
                bitmapToReuse.reconfigure(targetWidth, targetHeight, options.inPreferredConfig);
                bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, true);
                decodedBitmap = bitmapRegionDecoder.decodeRegion(regionToDecode, options);
            } catch (IOException e) {
                FLog.e(TAG, "Could not decode region %s, decoding full bitmap instead.", regionToDecode);
            } finally {
                if (bitmapRegionDecoder != null) {
                    bitmapRegionDecoder.recycle();
                }
            }
        }
        if (decodedBitmap == null) {
            decodedBitmap = BitmapFactory.decodeStream(inputStream, null, options);
        }
    } catch (IllegalArgumentException e) {
        mBitmapPool.release(bitmapToReuse);
        // This is thrown if the Bitmap options are invalid, so let's just try to decode the bitmap
        // as-is, which might be inefficient - but it works.
        try {
            // We need to reset the stream first
            inputStream.reset();

            Bitmap naiveDecodedBitmap = BitmapFactory.decodeStream(inputStream);
            if (naiveDecodedBitmap == null) {
                throw e;
            }
            return CloseableReference.of(naiveDecodedBitmap, SimpleBitmapReleaser.getInstance());
        } catch (IOException re) {
            // We throw the original exception instead since it's the one causing this workaround in the
            // first place.
            throw e;
        }
    } catch (RuntimeException re) {
        mBitmapPool.release(bitmapToReuse);
        throw re;
    } finally {
        mDecodeBuffers.release(byteBuffer);
    }

    if (bitmapToReuse != decodedBitmap) {
        mBitmapPool.release(bitmapToReuse);
        decodedBitmap.recycle();
        throw new IllegalStateException();
    }

    return CloseableReference.of(decodedBitmap, mBitmapPool);
}

From source file:org.mariotaku.gallery3d.GLImageLoader.java

protected Result decodeImage(final File file) {
    final String path = file.getAbsolutePath();
    try {/*from  w  w w.  j av a2  s  .co m*/
        final BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(path, false);
        final int width = decoder.getWidth();
        final int height = decoder.getHeight();
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = BitmapUtils.computeSampleSize(mFallbackSize / Math.max(width, height));
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        final Bitmap bitmap = decoder.decodeRegion(new Rect(0, 0, width, height), options);
        return Result.getInstance(decoder, bitmap, Exif.getOrientation(file), file);
    } catch (final IOException e) {
        return decodeBitmapOnly(file);
    }
}

From source file:com.jafme.mobile.activity.CropImageActivity.java

private Bitmap decodeRegionCrop(Rect rect, int outWidth, int outHeight) {
    // Release memory now
    clearImageView();//w w  w .  j av a 2 s .c  o m

    InputStream is = null;
    Bitmap croppedImage = null;
    try {
        is = getContentResolver().openInputStream(sourceUri);
        BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(is, false);
        final int width = decoder.getWidth();
        final int height = decoder.getHeight();

        if (exifRotation != 0) {
            // Adjust crop area to account for image rotation
            Matrix matrix = new Matrix();
            matrix.setRotate(-exifRotation);

            RectF adjusted = new RectF();
            matrix.mapRect(adjusted, new RectF(rect));

            // Adjust to account for origin at 0,0
            adjusted.offset(adjusted.left < 0 ? width : 0, adjusted.top < 0 ? height : 0);
            rect = new Rect((int) adjusted.left, (int) adjusted.top, (int) adjusted.right,
                    (int) adjusted.bottom);
        }

        try {
            croppedImage = decoder.decodeRegion(rect, new BitmapFactory.Options());

            //  ?  

            if (exifRotation != 0) {

                final Matrix matrix = new Matrix();
                matrix.setRotate(exifRotation);
                croppedImage = Bitmap.createBitmap(croppedImage, 0, 0, croppedImage.getWidth(),
                        croppedImage.getHeight(), matrix, true);

                exifRotation = 0;
            }

            int croppedWidth = croppedImage.getWidth();
            int croppedHeight = croppedImage.getHeight();
            if (croppedWidth > outWidth || croppedHeight > outHeight) {
                Matrix matrix = new Matrix();
                matrix.postScale((float) outWidth / croppedWidth, (float) outHeight / croppedHeight);
                croppedImage = Bitmap.createBitmap(croppedImage, 0, 0, croppedWidth, croppedHeight, matrix,
                        true);
            }

        } catch (IllegalArgumentException e) {
            // Rethrow with some extra information
            throw new IllegalArgumentException("Rectangle " + rect + " is outside of the image (" + width + ","
                    + height + "," + exifRotation + ")", e);
        }

    } catch (IOException e) {
        Log.e(LOG_TAG, "Error cropping image: " + e.getMessage(), e);
        finish();
    } catch (OutOfMemoryError e) {
        Log.e(LOG_TAG, "OOM cropping image: " + e.getMessage(), e);
        setResultException(e);
    } finally {
        CropUtil.closeSilently(is);
    }
    return croppedImage;
}