定期,你可以只寫BitmapFactory.decodeBitmap(....)等,但該文件可以是巨大的,你可以得到的OutOfMemoryError很快,特別是,如果你在一行中解碼幾次。因此,您需要在將圖像設置爲查看前壓縮圖像,以免內存不足。這是做到這一點的正確方法。
File f = new File(path);
if(file.exists()){
Bitmap myBitmap = ImageHelper.getCompressedBitmap(photoView.getMaxWidth(), photoView.getMaxHeight(), f);
photoView.setImageBitmap(myBitmap);
}
//////////////
/**
* Compresses the file to make a bitmap of size, passed in arguments
* @param width width you want your bitmap to have
* @param height hight you want your bitmap to have.
* @param f file with image
* @return bitmap object of sizes, passed in arguments
*/
public static Bitmap getCompressedBitmap(int width, int height, File f) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(f.getAbsolutePath(), options);
options.inSampleSize = calculateInSampleSize(options, width, height);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(f.getAbsolutePath(), options);
}
/////////////////
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height/2;
final int halfWidth = width/2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight/inSampleSize) >= reqHeight
&& (halfWidth/inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
你收到的一些錯誤,是文件存在於這條道路?檢查此:http://stackoverflow.com/questions/4181774/show-image-view-from-file-path –
我沒有得到任何錯誤。路徑是正確的。我沒有得到圖像。不知道,如果我設置正確的方式 –
確保您有閱讀權限:<使用權限android:name =「android.permission.READ_EXTERNAL_STORAGE」/>,也請確保文件不是很大 –