Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ParseImageView.loadInBackground() should scale down images to prevent OutOfMemoryException (code inside) #132

Open
M3psipax opened this issue Feb 18, 2016 · 0 comments

Comments

@M3psipax
Copy link

Like so:

public Task<byte[]> loadInBackground() {
    if (file == null) {
      return Task.forResult(null);
    }
    final ParseFile loadingFile = file;
    return file.getDataInBackground().onSuccessTask(new Continuation<byte[], Task<byte[]>>() {
      @Override
      public Task<byte[]> then(Task<byte[]> task) throws Exception {
        byte[] data = task.getResult();
        if (file != loadingFile) {
          // This prevents the very slim chance of the file's download finishing and the callback
          // triggering just before this ImageView is reused for another ParseObject.
          return Task.cancelled();
        }
        if (data != null) {
          measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
          // Get the dimensions of the View
          int targetW = getWidth();
          int targetH = getHeight();

          // Get the dimensions of the bitmap
          BitmapFactory.Options bmOptions = new BitmapFactory.Options();
          bmOptions.inJustDecodeBounds = true;
          BitmapFactory.decodeByteArray(data, 0, data.length, bmOptions);
          int photoW = bmOptions.outWidth;
          int photoH = bmOptions.outHeight;

          // Determine how much to scale down the image
          int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

          // Decode the image file into a Bitmap sized to fill the View
          bmOptions.inJustDecodeBounds = false;
          bmOptions.inSampleSize = scaleFactor;
          Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, bmOptions);
          if (bitmap != null) {
            setImageBitmap(bitmap);
          }
        }
        return task;
      }
    }, Task.UI_THREAD_EXECUTOR);
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant