[英]Get Image from path
我想從Album獲取圖像,但是當我選擇任何圖片時,它不會顯示並停止。 我用手機進行測試,我想問題可能是我用代碼設置了錯誤的路徑。 但是我找不到它在哪里。 案例100:采取行動,並且可以正常工作;案例101:采取行動。
這是我的onActivityResult
protected void **onActivityResult**(int requestCode , int resultCode , Intent
data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK ) {
switch (requestCode)
{
case 100:
Intent it = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
sendBroadcast(it);
break;
case 101:
imgUri = convertUri(data.getData());
break;
}
showImg();
}
else {
Toast.makeText(this , requestCode==100? "no take the pic" : "no choose the pic" , Toast.LENGTH_LONG).show();
}
}
這是我的轉換
Uri convertUri(Uri uri){
if(uri.toString().substring(0,7).equals("content"))
{
String[] colName = {MediaStore.MediaColumns.DATA};
Cursor cursor = getContentResolver().query(uri,colName,null,null,null);
cursor.moveToFirst();
uri = Uri.parse("file://"+ cursor.getString(0));
}
return uri;
}
這是我的表演
void showImg(){
imv = (ImageView) findViewById(R.id.imageView);
int iw ,ih , vw, vh;
boolean needRotate;
BitmapFactory.Options option = new BitmapFactory.Options();
option.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imgUri.getPath(),option);
iw = option.outWidth;
ih = option.outHeight;
vw = imv.getWidth();
vh = imv.getHeight();
int scaleFactor;
if(iw<ih)
{
needRotate = false;
scaleFactor = Math.min(iw/vw , ih/vh);
}else{
needRotate = true ;
scaleFactor =Math.min( ih / vw , iw/vh);
}
option.inJustDecodeBounds = false;
option.inSampleSize = scaleFactor ;
Bitmap bmp = BitmapFactory.decodeFile(imgUri.getPath(),option);
if(needRotate)
{
Matrix matrix = new Matrix();
matrix.postRotate(90);
bmp = Bitmap.createBitmap(bmp , 0 , 0 ,bmp.getWidth(), bmp.getHeight(), matrix , true);
}
imv.setImageBitmap(bmp);
}
您嘗試獲取文件系統路徑的方法有誤。
最好從onActivityResult污穢地使用data.getData()uri。
Bitmap bmp = BitmapFactory.decodeFile(imgUri.getPath(),option);
改成:
InputStream is = getContentResolver().openInputStream(data.getData());
Bitmap bmp = BitmapFactory.decodeStream(is, option);
第一次通話時執行相同操作。 您可以使用is
只有一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.