定期,你可以只写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”/>,也请确保文件不是很大 –