我的代码出错:内存不足错误
以下是我的代码:
public class ViewFullImage extends Activity {
//Bitmap bitmap;
private Bitmap bitmap;
private ImageView iv;
private String ImgFile_Name;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.view_draw_picture);
Log.v("","===================== viewFullImage.java================");
try{
String path = "mfc/cam_img/";
int s_id=getIntent().getIntExtra("s_id", -1);
int intentKey=getIntent().getIntExtra("iv", -1);
iv = (ImageView)findViewById(R.id.iv_display);
File Dir= Environment.getExternalStorageDirectory();
File imageDirectory = new File(Dir,path);
File file = new File(imageDirectory, "img_"+s_id+"_"+intentKey+".jpg");
ImgFile_Name = file.getAbsolutePath();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = 1;
BitmapFactory.decodeFile(file.getAbsolutePath(),options);
int h = options.outHeight;
int w = options.outWidth;
Log.v("","This is h : "+h);
Log.v("","This is w : "+w);
bitmap = BitmapFactory.decodeFile(ImgFile_Name,options);
iv = (ImageView)findViewById(R.id.image);
if(h<w)
{
iv.setImageBitmap(rotateBitmap(bitmap));
}
else{
iv.setImageBitmap(bitmap);
}
}catch (Exception e) {
// TODO: handle exception
Log.v("","Exception : "+e);
}
}
Bitmap rotateBitmap(Bitmap bitmap)
{
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(),
matrix, true);
bitmap.recycle();
bitmap=null;
return bitmap1;
}
}
在这堂课中我试图从SD卡中显示图像。我从其他活动中调用此活动,例如:
Intent intent =new Intent(cxt,ViewFullImage.class);
intent.putExtra("iv", 8);
intent.putExtra("s_id", s_id);
startActivity(intent);
请有人告诉我在哪里做错误.....
答案 0 :(得分:1)
你没有做错任何事情,你不能在Android中分配一个图像(甚至一个大字符串)而不知道它是否适合内存。
问题出现在Android 4设备中,因为有更多的4.0设备,只有16MB堆。内存堆是您打开图像的内存。
要解决此问题,您应该根据需要缩放图像(取决于堆大小和图像大小)。以下是如何使用缩放解码的代码:
public static Bitmap decodeSampleImage(File f, int width, int height) {
try {
System.gc(); // First of all free some memory
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// The new size we want to scale to
final int requiredWidth = width;
final int requiredHeight = height;
// Find the scale value (as a power of 2)
int sampleScaleSize = 1;
while (o.outWidth / sampleScaleSize / 2 >= requiredWidth && o.outHeight / sampleScaleSize / 2 >= requiredHeight)
sampleScaleSize *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = sampleScaleSize;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (Exception e) {
Log.d(TAG, e.getMessage()); // We don't want the application to just throw an exception
}
return null;
}
另一件事是,如果您没有释放一些内存(System.gc())并且您在许多图片之间单击/切换,则无论如何您可能会耗尽内存。如果内存不足,则不想破坏应用程序,而是管理Bitmap为空的情况。您也可以改进异常的捕获案例。
希望它有所帮助。