ParseUI-Android icon indicating copy to clipboard operation
ParseUI-Android copied to clipboard

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

Open M3psipax opened this issue 9 years ago • 0 comments

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

M3psipax avatar Feb 18 '16 13:02 M3psipax