Out of memory error when loading bitmap from Uri
<p>I am using the following method to get the <code>Bitmap</code> from a <code>Uri</code> :</p>

<pre><code>private static Bitmap getBitmapFromUri(@NonNull Context context, @NonNull Uri uri) throws IOException {

        ParcelFileDescriptor parcelFileDescriptor =
                context.getContentResolver().openFileDescriptor(uri, "r");
        assert parcelFileDescriptor != null;
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        parcelFileDescriptor.close();
        return image;
    }
</code></pre>

<p>The problem is, I am sometimes getting OOM errors in the return statement from <code>Crashlytics</code>. I assume it is happening because the selected image is of a large size. How do modify it so as to return the best quality scaled down version of Bitmap so that it does not cause Out of memory error?</p>

<p><strong>Edit</strong> I have posted an answer myself. Please have a look and let me know it is the correct way to do it.</p>