Android編程---通過(guò)自帶文件瀏覽器獲取并加載本地圖片
話不多說(shuō)求泰,直接上代碼卤唉。
第一步
private void sendPhotoOne(){
/*
使用自帶文件瀏覽器選擇文件
*/
? Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
? intent.setType("image/*");? //設(shè)置要過(guò)濾的文件格式
? 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傳給轉(zhuǎn)換方法低飒,并返回一個(gè)bitmap對(duì)象
iv_show_photoOne.setImageBitmap(bitmap);
}
}
}
第三步
/*
根據(jù)傳入的URI轉(zhuǎn)換成Bitmap對(duì)象
*/
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;
}