700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Android获取手机相册图片

Android获取手机相册图片

时间:2022-01-28 01:25:23

相关推荐

Android获取手机相册图片

1.在AndroidManifest.XML中添加权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

2.使用Intent

在Activity Action里面有一个“ACTION_GET_CONTENT”字符串常量,该常量让用户选择特定类型的数据,并返回该数据的URI.我们利用该常量,

然后设置类型为“image/*”,就可获得android手机内的所有image。

Intent intent1= new Intent();

intent1.setAction(Intent.ACTION_GET_CONTENT);

intent1.addCategory(Intent.CATEGORY_OPENABLE);

intent1.setType("image/*");

在onCreate中开启onActivityResult

startActivityForResult(intent1,111);

复写onActivityResult读取选择图片的uri

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data){

super.onActivityResult(requestCode,resultCode,data);

switch (requestCode){

case 111:

if(resultCode ==RESULT_CANCELED) {

Toast.makeText(getApplication(), "点击取消从相册选择", Toast.LENGTH_LONG).show();

return;

}

try{

Uri uri = data.getData();

Log.e("TAG",uri.toString());

String filePath = getRealPathFromURI(uri);

bitmap1 = getresizePhoto(filePath);

imageView1.setImageBitmap(bitmap1);

if(bitmap1!=null){

Log.e("aa","bitmap1不为空!!!!!!!!!!");

}else{

Log.e("aa","bitmap1为空!!!!!!!!!!");

}

}catch (Exception e){

e.printStackTrace();

}

break;

}

}

某个uri格式:uri: content://media/external/images/media/614016

某个图片路径 /storage/emulated/0/DCIM/P70713-115542.jpg

从URI获取String类型的文件路径

public String getRealPathFromURI(Uri contentUri){

Cursor cursor = null;

try{

String [] proj = {MediaStore.Images.Media.DATA};

//由context.getContentResolver()获取contentProvider再获取cursor(游

//标)用游标获取文件路径返回

cursor = context.getContentResolver().query(contentUri,proj,null,null,null);

cursor.moveToFirst();

int column_indenx = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

return cursor.getString(column_indenx);

} finally {

if (cursor != null) {

cursor.close();

}

}

}

3.根据文件路径调整图片大小防止OOM并且返回bitmap

private Bitmap getresizePhoto(String ImagePath){

if (ImagePath!=null){

BitmapFactory.Options options = new BitmapFactory.Options();

options.inJustDecodeBounds = true;

BitmapFactory.decodeFile(ImagePath,options);

double ratio = Math.max(options.outWidth*1.0d/1024f,options.outHeight*1.0d/1024);

options.inSampleSize = (int) Math.ceil(ratio);

options.inJustDecodeBounds= false;

Bitmap bitmap=BitmapFactory.decodeFile(ImagePath,options);

return bitmap;

}

return null;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。