Browse files

Use BitmapRegionDecoder to efficiently crop images on Android

The Android ImageEditingManager is inefficient and slow when cropping images. It loads the full resolution image into memory and then crops it. This leads to slow performance and occasional OutOfMemory Exceptions.
[BitmapRegionDecoder]( can be used to crop without needing to load the full resolution image into memory. Using it is much more efficient and much faster.

Relevant issue: #10470

Attempt to crop a very large image (2000x2000) on Android. With this change, the crop should happen almost instantly. On the master branch, it should take 2-3 seconds (and might run out of memory).

Please let me know if there's anything else I can provide.
Closes #15439

Differential Revision: D5628223

Pulled By: shergin

fbshipit-source-id: bf314e76134cd015380968ec4533225e724c4b26
  • Loading branch information...
faifai21 authored and facebook-github-bot committed Sep 26, 2017
1 parent e6596dc commit 64ffe4516ec755505339a0a107efa83c3d4c9771
@@ -28,8 +28,10 @@
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
@@ -298,17 +300,17 @@ protected void doInBackgroundGuarded(Void... params) {
private Bitmap crop(BitmapFactory.Options outOptions) throws IOException {
InputStream inputStream = openBitmapInputStream();
// Effeciently crops image without loading full resolution into memory
BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(inputStream, false);
try {
// This can use a lot of memory
Bitmap fullResolutionBitmap = BitmapFactory.decodeStream(inputStream, null, outOptions);
if (fullResolutionBitmap == null) {
throw new IOException("Cannot decode bitmap: " + mUri);
return Bitmap.createBitmap(fullResolutionBitmap, mX, mY, mWidth, mHeight);
Rect rect = new Rect(mX, mY, mX + mWidth, mY + mHeight);
return decoder.decodeRegion(rect, outOptions);
} finally {
if (inputStream != null) {

0 comments on commit 64ffe45

Please sign in to comment.