[英]Cannot load Image from file:// path in Picasso
我正在嘗試使用Picasso
將ImageView
從圖庫加載到ImageView
。
這是代碼
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode!= Activity.RESULT_OK) return;
switch (requestCode) {
case PICK_GALLERY_IMAGE_REQUEST: {
Uri imageUri = data.getData();
Log.d(DEBGUG_TAG,"Image URI: "+imageUri.toString());
Picasso picasso = Picasso.with(getApplicationContext());
picasso.setLoggingEnabled(true);
picasso.load(imageUri).error(R.drawable.c).into(testImgView, new com.squareup.picasso.Callback(){
@Override
public void onSuccess() {
Log.d(DEBGUG_TAG,"Success loading image from uri:PICASSO");
}
@Override
public void onError() {
Log.d(DEBGUG_TAG,"Cannot load image");
}
});
問題是從圖庫中選擇圖像時會返回文件路徑
D/debug: Image URI: file:///storage/emulated/0/DCIM/Camera/IMG_20170126_211524.jpg
這似乎不適用於Picasso,因為返回錯誤並記錄D/debug: Cannot load image
以錯誤方法D/debug: Cannot load image
。
但是,從另一個返回Uri
應用中選擇相同的圖像,例如: D/debug: Image URI: content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F90455/ORIGINAL/NONE/1757236944
成功。
有什么辦法從文件路徑加載圖像嗎?
不要使用file://,就像這樣使用它:
Uri targetUri = data.getData();
if (data.toString().contains("content:")) {
imagePath = getRealPathFromURI(targetUri);
} else if (data.toString().contains("file:")) {
imagePath = targetUri.getPath();
} else {
imagePath = null;
}
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = getContentResolver().query(contentUri, proj, null, null,
null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
嘗試以下代碼:
File imgFile = new File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
嘗試使用ImageView的內置方法setImageURI獲取本地文件
testImgView.setImageURI(Uri.parse(imageUri));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.