获取图库照片
当要进分享照片功能时,点击一个按钮,然后进入图库选择照片,
要进行这样的操作,改怎么完成呢,要解决2个问题:
1、该如何进入图库
2、改如何取得照片
==================================================
进入图库:
?
? ? ? ? ? ? ? ? Intent intent = new Intent(); ?
? ? ? ? ? ? ? ? intent.setType("image/*"); ?
? ? ? ? ? ? ? ? intent.setAction(Intent.ACTION_GET_CONTENT); ??
? ? ? ? ? ? ? ? /* 取得相片后返回本画面 */ ?
? ? ? ? ? ? ? ? startActivityForResult(intent, 1);
?选取照片:
? ? ? ? ? ? ? ?当点击照片后,会返回一个intent,那么,用getData();获得一个URI的数据,这个uri就是图片在数据库中的位置
? ? ? ? ? ? ? ?然后该怎么通过这个uri操作,得到图片和路径呢??看下面源码吧
====================================================
最后详细的见源码
?
public class StartActivityForResult extends Activity {
? ? /** Called when the activity is first created. */
? ? @Override
? ? public void onCreate(Bundle savedInstanceState) {
? ? ? ? super.onCreate(savedInstanceState);
? ? ? ? setContentView(R.layout.main);
? ? ? ??
? ? ? ? Button button = (Button)findViewById(R.id.btn); ?
? ? ? ? button.setText("选择图片"); ?
? ? ? ? button.setOnClickListener(new Button.OnClickListener(){ ?
? ? ? ? ? ? @Override ?
? ? ? ? ? ? public void onClick(View v) { ?
? ? ? ? ? ? ? ?Intent intent = new Intent(); ?
? ? ? ? ? ? ? ? intent.setType("image/*"); ?
? ? ? ? ? ? ? ? intent.setAction(Intent.ACTION_GET_CONTENT); ??
? ? ? ? ? ? ? ? /* 取得相片后返回本画面 */ ?
? ? ? ? ? ? ? ? startActivityForResult(intent, 1); ?
?
? ? ? ? ? ? } ?
? ? ? ? ? ? ??
? ? ? ? }); ?
? ? } ?
? ? ??
? ? @Override ?
? ? protected void onActivityResult(int requestCode, int resultCode, Intent data) { ?
? ? ? ? if (resultCode == RESULT_OK) { ?
? ? ? ? ? ? Uri uri = data.getData(); ?
? ? ? ? ? ? Log.e("uri", uri.toString());?
? ? ? ? ? ? Log.e("uri", uri.getPath()); ?
? ? ? ? ? ? ContentResolver cr = this.getContentResolver();?
?
? ? ? ? ? ? //获得照片,并显示
? ? ? ? ? ? try { ?
? ? ? ? ? ? ? ? Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri)); ?
? ? ? ? ? ? ? ? ImageView imageView = (ImageView) findViewById(R.id.iv); ?
? ? ? ? ? ? ? ? /* 将Bitmap设定到ImageView */ ?
? ? ? ? ? ? ? ? imageView.setImageBitmap(bitmap); ?
? ? ? ? ? ? } catch (FileNotFoundException e) { ?
? ? ? ? ? ? ? ? Log.e("Exception", e.getMessage(),e); ?
? ? ? ? ? ? }
? ? ? ? ? ??
? ? ? ? ? ? //获得照片路径
? ? ? ? ? ? //get the picture path
? ? ? ? ? ? String[] projection = { MediaStore.Images.Media.DATA };
? ? ? ? ? ? Cursor cursor = managedQuery(uri, projection, null, null, null);
? ? ? ? ? ? int column_index = cursor
? ? ? ? ? ? ? ? ? ? .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
? ? ? ? ? ? cursor.moveToFirst();
? ? ? ? ? ? System.out.println("image path ===>" + cursor.getString(column_index));
? ? ? ? ? ??
? ? ? ? } ?
? ? ? ? super.onActivityResult(requestCode, resultCode, data); ?
? ? } ?
}