Android获取手机相册中图片
程序员文章站
2022-06-17 22:24:17
Android读取手机相册的实现...
1、添加内存读/写权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2、代码实现
//通过按钮点击事件触发,使用Intent打开相册
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, IMAGE);
}
//Intent回调
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//获取图片路径
if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumns = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePathColumns[0]);
String imagePath = c.getString(columnIndex);
c.close();
}
3、在ImageView中显示
private void showImage(String imaePath) {
//推荐Glide
Glide.with(this)
.load(imagePath)
.error(R.mipmap.ic_launcher)
.into(iv_add_shose);
//也可以
Bitmap bitmap = BitmapFactory.decodeFile(imaePath);
img.setImageBitmap(bitmap);
}
本文地址:https://blog.csdn.net/weixin_43742354/article/details/103850125