我正在尝试从设备存储中获取文件并在图像视图中显示它。 有时候它工作得非常好,但有时却没有。虽然位图在那里,但图像视图仍然是黑色。
请建议。
file:/storage/emulated/0/Download/Full-hd-nature-wallpapers-free-download2.jpg
public static Bitmap convertToBitmap(File file){
URI uri = null;
try {
uri = file.toURI();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap bmp = BitmapFactory.decodeStream(uri.toURL().openStream(), new Rect(), options);
//bmp.recycle();
return bmp;
} catch (Exception e) {
return null;
}//catch
}
imageViewPatientImage.setImageBitmap(convertToBitmap(new File(mImagePath));
答案 0 :(得分:0)
试试这个:
Bitmap bitmap = getThumbnail(uri);
showImage.setImageBitmap(bitmap);
传递优化位图:
public Bitmap getThumbnail(Uri uri) throws FileNotFoundException, IOException{
InputStream input = getContext().getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither=true;//optional
onlyBoundsOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
input.close();
if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))
return null;
int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;
double ratio = (originalSize > 500) ? (originalSize / 500) : 1.0;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
bitmapOptions.inDither=true;//optional
bitmapOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
input = getContext().getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
input.close();
return bitmap;
}
private static int getPowerOfTwoForSampleRatio(double ratio){
int k = Integer.highestOneBit((int)Math.floor(ratio));
if(k==0) return 1;
else return k;
}