我需要从图库中获取图像,并将其转换为位图。
这是发送意图的代码:
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
onActivityResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == mResultLoadImage && resultCode == RESULT_OK && data != null) {
Uri pickedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath,
null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor
.getColumnIndex(filePath[0]));
bitmap = BitmapFactory.decodeFile(imagePath);
someFunction(bitmap);
cursor.close();
}
}
我总是得到一个NullPointerException,并且使用debuger,我发现数据Intent为null。 任何解决方案?
答案 0 :(得分:-1)
试试这个,它应该有效:
Intent intent = new Intent(Intent.ACTION_PICK);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE) {
Uri imageUri = data.getData();
Bitmap imgBitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri), null, null);
// then do whatever you want with the bitmap
}
}