Skip to content

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

@M3psipax

Description

@M3psipax

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);
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions