Android How to - Read Bitmap from a Uri








Question

We would like to know how to read Bitmap from a Uri.

Answer

//from   ww  w  . j  a v  a 2 s.  c om
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

public class Main {

    public static Bitmap readShrink(Context context, Uri uri, int size) {

        InputStream readStream = null;
        InputStream writeStream = null;
        try {
            readStream = context.getContentResolver().openInputStream(uri);
            BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
            bmpFactoryOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(readStream, null, bmpFactoryOptions);

            int ratio = (int) Math.min(bmpFactoryOptions.outWidth / (float) size,
                    bmpFactoryOptions.outHeight / (float) size);
            bmpFactoryOptions.inSampleSize = ratio;
            bmpFactoryOptions.inJustDecodeBounds = false;

            writeStream = context.getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(writeStream, null, bmpFactoryOptions);
            return bitmap;
        } catch (FileNotFoundException e) {
        } finally {
            try {
                readStream.close();
            } catch (IOException e) {
            }
            try {
                writeStream.close();
            } catch (IOException e) {
            }
        }
        return null;
    }
}