Android调用手机自带图库选择图片

来源:互联网 发布:科比2004年总决赛 数据 编辑:程序博客网 时间:2024/04/28 08:46

       这里我们采用的布局文件中 有一个ImageView(set_pic)和Button,布局较为简单(这里就不再给出)。其中Button用于打开手机自带图库进行选择图片,而ImageView就用于显示选中的文件。

       Button注册了点击事件监听器,内部代码如下:


// 调用android自带的图库Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);startActivityForResult(intent, ActivityRequestCode.SHOW_MAP_DEPOT);

其中ActivityRequestCode.SHOW_MAP_DEPOT只是一个常量,作为请求码,表示活动:

public interface ActivityRequestCode {public static final int SHOW_MAP_DEPOT = 1; //显示Android自带图库,用于选择用户自己的图片}
其中调用android自带图库的那个活动还需添加一个回调方法,用于接收自带图库返回的图片路径:

public void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (data != null) {if (requestCode == ActivityRequestCode.SHOW_MAP_DEPOT&& resultCode == Activity.RESULT_OK)showYourPic(data);}}

// 调用android自带图库,显示选中的图片private void showYourPic(Intent data) {Uri selectedImage = data.getData();String[] filePathColumn = { MediaStore.Images.Media.DATA };Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);cursor.moveToFirst();int columnIndex = cursor.getColumnIndex(filePathColumn[0]);String picturePath = cursor.getString(columnIndex);cursor.close();if (picturePath.equals(""))return;pic_path = picturePath; // 保存所添加的图片的路径// 缩放图片, width, height 按相同比例缩放图片BitmapFactory.Options options = new BitmapFactory.Options();// options 设为true时,构造出的bitmap没有图片,只有一些长宽等配置信息,但比较快,设为false时,才有图片options.inJustDecodeBounds = true;Bitmap bitmap = BitmapFactory.decodeFile(picturePath, options);int scale = (int) (options.outWidth / (float) 300);if (scale <= 0)scale = 1;options.inSampleSize = scale;options.inJustDecodeBounds = false;bitmap = BitmapFactory.decodeFile(picturePath, options);set_pic.setImageBitmap(bitmap);set_pic.setMaxHeight(350);set_pic.setVisibility(ImageView.VISIBLE);}
这样我们就可以使用android自带图库选择图片了。


2 0
原创粉丝点击