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

       这里我们采用的布局文件中 有一个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自带图库选择图片了。


  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值