decode Uri to Bitmap - Android Graphics

Android examples for Graphics:Bitmap URL

Description

decode Uri to Bitmap

Demo Code


//package com.java2s;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;

import android.content.Context;

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

import android.os.ParcelFileDescriptor;

public class Main {
    public static Bitmap decodeUri(Context context, Uri uri) {
        ParcelFileDescriptor parcelFD = null;
        try {/*  w  w w.  j  a  v a2 s  .c o m*/
            parcelFD = context.getContentResolver().openFileDescriptor(uri,
                    "r");
            FileDescriptor imageSource = parcelFD.getFileDescriptor();

            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFileDescriptor(imageSource, null, o);

            //the new size we want to scale to 
            final int REQUIRED_SIZE = 320;

            //Find the correct scale value. It should be the power of 2. 2???
            int width_tmp = o.outWidth;
            int height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) {
                    break;
                }
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            Bitmap bitmap = BitmapFactory.decodeFileDescriptor(imageSource,
                    null, o2);
            return bitmap;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related Tutorials