BitmapFactory.decodeFile : java.lang.OutOfMemoryError

Programming/Android 2017. 3. 24. 09:10 Posted by 생각하는로뎅
반응형

1. 에러 메세지


java.lang.OutOfMemoryError

at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)

at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:613)

at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:589)

at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:369)

at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:395)




2. 해결 방법



Uri path = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
// intent 의 여분 데이터로 저장된 비트맵 이미지를 얻는다.
//Bitmap bmp = (Bitmap) data.getExtras().get("data");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPurgeable = true; // 메모리를 줄여주는 옵션
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inSampleSize = calculateInSampleSize(options, resizeHeight, resizeHeight);
options.inJustDecodeBounds = false;
options.inDither = true; // 이미지를 깔끔하게 처리해서 보여주는 옵션

Bitmap bmp = BitmapFactory.decodeFile(fileFullPath, options);
/**
* 이미지의 샘플사이즈를 계산한다.
* @author 임성진
* @version 2.0.0
* @since 2017-03-31 오전 9:16
* @params
* @return
*/
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {

// Raw height and width of image
int height = options.outHeight;
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;
}


반응형