Not able to pick photo from gallery?
我能够打开画廊并获得画廊的路径为=
内容://媒体/外部/图像/媒体/ 2
但无法在imageview中解码
这是我的代码
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | b=(Button) findViewById(R.id.Button01); b.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { // in onCreate or any event where your want the user to // select a file Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent,IMAGE_PICK); } }); } //UPDATED public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == IMAGE_PICK) { Uri selectedImageUri = data.getData(); //OI FILE Manager filemanagerstring = selectedImageUri.getPath(); //MEDIA GALLERY selectedImagePath = getPath(selectedImageUri); if(selectedImagePath!=null) { path = selectedImageUri.toString(); m1.setPath(path); BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; Bitmap yourSelectedImage = BitmapFactory.decodeFile(path, options); ImageButton img2=(ImageButton)findViewById(R.id.widget27); img2.setImageBitmap(yourSelectedImage); Toast.makeText(getBaseContext(), path, 1000).show(); } } } } public String getPath(Uri uri) { String [] proj={MediaStore.Images.Media.DATA}; Cursor cursor = managedQuery(uri, proj, // Which columns to return null, // WHERE clause; which rows to return (all rows) null, // WHERE clause selection arguments (none) null); // Order-by clause (ascending by name) int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); |
}
}
请提前帮助谢谢
这段代码应该放在你的onActivityResult中。 它为您提供了从获取的图像URI解码文件路径的方法:
1 2 3 4 5 6 7 | Uri selectedImageUri = data.getData(); String[] projection = { MediaStore.Images.Media.DATA}; Cursor cursor = managedQuery(selectedImageUri, projection, null, null, null); int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); selectedImagePath = cursor.getString(column_index_data); Bitmap galleryImage = BitmapFactory.decodeFile(selectedImagePath); |
我们需要在早期的onActivityResult()的图库选择器代码中进行以下更改/修复,以便在Kitkat和所有其他早期版本上无缝运行。
Uri selectedImgFileUri = data.getData();
if(selectedImgFileUri == null){
1 | // user has not selected any photo |
}
尝试{
InputStream input = mActivity.getContentResolver()。openInputStream(selectedImgFileUri);
mSelectedPhotoBmp = BitmapFactory.decodeStream(输入);
} catch(Throwable tr){
//显示要重试的消息
}