我正在尝试使用ImageView
将图片加载到图库中的Picasso
。
以下是代码
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
。
然而,从另一个返回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
成功。
以任何方式从文件路径加载图片?
答案 0 :(得分:6)
不要使用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();
}
}
}
答案 1 :(得分:2)
请尝试以下代码:
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);
}
答案 2 :(得分:1)
为本地文件尝试 ImageView 的内置方法 setImageURI
import copy
from colorlog import ColoredFormatter
import scrapy.utils.log
color_formatter = ColoredFormatter(
(
'%(log_color)s%(levelname)-5s%(reset)s '
'%(yellow)s[%(asctime)s]%(reset)s'
'%(white)s %(name)s %(funcName)s %(bold_purple)s:%(lineno)d%(reset)s '
'%(log_color)s%(message)s%(reset)s'
),
datefmt='%y-%m-%d %H:%M:%S',
log_colors={
'DEBUG': 'blue',
'INFO': 'bold_cyan',
'WARNING': 'red',
'ERROR': 'bg_bold_red',
'CRITICAL': 'red,bg_white',
}
)
_get_handler = copy.copy(scrapy.utils.log._get_handler)
def _get_handler_custom(*args, **kwargs):
handler = _get_handler(*args, **kwargs)
handler.setFormatter(color_formatter)
return handler
scrapy.utils.log._get_handler = _get_handler_custom