Android编程---通过自带文件浏览器获取并加载本地图片
话不多说,直接上代码。
第一步
private void sendPhotoOne(){
/*
使用自带文件浏览器选择文件
*/
Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*"); //设置要过滤的文件格式
startActivityForResult(intent,1);
}
第二步
/*
重写onActivityResult()方法,得到返回的uri
*/
@Override
protected void onActivityResult(int requestCode,int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode ==RESULT_OK) {
if (requestCode ==1) {
Uri uri = data.getData();
Bitmap bitmap = getBitmapFromUri(uri);//将得到的uri传给转换方法,并返回一个bitmap对象
iv_show_photoOne.setImageBitmap(bitmap);
}
}
}
第三步
/*
根据传入的URI转换成Bitmap对象
*/
private Bitmap getBitmapFromUri(Uri uri) {
Bitmap bitmap =null;
try {
BitmapFactory.Options options =new BitmapFactory.Options();
int picWidth = options.outWidth;
int picHeight = options.outHeight;
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
options.inSampleSize =1;
if (picWidth > picHeight) {
if (picWidth > screenWidth)
options.inSampleSize = picWidth / screenWidth;
}else {
if (picHeight > screenHeight)
options.inSampleSize = picHeight / screenHeight;
}
options.inJustDecodeBounds =false;
bitmap = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(uri),null, options);
}catch (Exception e) {
e.printStackTrace();
return null;
}
return bitmap;
}
网友评论