通常我们在选取图片的时候在onActivityResult回调中调用intent.getData()拿到uri对象。下面来讲解如何根据这个uri获取到Bitmap对象。
首先,在Android的API中有一个MediaStore.Images.Media类,这个类有一个getBitmap静态方法用来根据Uri获取到Bitmap的对象。方法有两个参数。我们看到源码方法:
public static final Bitmap getBitmap(ContentResolver cr, Uri url) throws FileNotFoundException, IOException { throw new RuntimeException("Stub!"); }
第一个传的是ContenProvider组件的ContentResolver对象,通常传入的是Context对象的getContentResolver()方法;
第二个参数传的就是我们提供的Uri数据。方法反回来就是Bitmap对象了。
代码实例:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}