parse-community / ParseUI-Android

ParseUI contains user interface libraries for building apps with the Parse Android SDK.
Other
592 stars 324 forks source link

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

Open M3psipax opened 8 years ago

M3psipax commented 8 years ago

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