Android OOMメモリオーバーフローソリューションの1つ
2013 ワード
1.画像メモリオーバーフロー
デフォルトでは、androidプログラムごとのdailvik仮想マシンの最大スタックサイズは16 Mです.
ロードされた画像が多すぎたり、画像が大きすぎたりすると、OOMの問題がよく発生します.
Androidでbitmapを使うとメモリが溢れやすく、Javaというエラーが発生します.lang.OutOfMemoryError
2.解決策
デフォルトでは、androidプログラムごとのdailvik仮想マシンの最大スタックサイズは16 Mです.
ロードされた画像が多すぎたり、画像が大きすぎたりすると、OOMの問題がよく発生します.
Androidでbitmapを使うとメモリが溢れやすく、Javaというエラーが発生します.lang.OutOfMemoryError
2.解決策
public Bitmap matrixBitmapSize(Bitmap bitmap, int screenWidth,
int screenHight) {
// bitmap
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
float scale = (float) screenWidth / w;
float scale2 = (float) screenHight / h;
//
scale = scale < scale2 ? scale : scale2;
// scale .
matrix.postScale(scale, scale);
// w,h .
return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
}
public Bitmap optionsBitmapSize(String imagePath, int screenWidth,
int screenHight) {
//
BitmapFactory.Options options = new Options();
// true
options.inJustDecodeBounds = true;
// null
BitmapFactory.decodeFile(imagePath, options);
//
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;
//
int scaleWidth = imageWidth / screenWidth;
int scaleHeight = imageHeight / screenHight;
// 1
int scale = 1;
//
if (scaleWidth > scaleHeight & scaleHeight >= 1) {
scale = scaleWidth;
} else if (scaleHeight > scaleWidth & scaleWidth >= 1) {
scale = scaleHeight;
}
// true
options.inJustDecodeBounds = false;
//
options.inSampleSize = scale;
// scale
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
return bitmap;
}