안드로이드 큰 이미지를 효율적으로 로드하는 방법

프로그래밍/Android 2013. 8. 30. 09:38

안드로이드 큰 이미지를 효율적으로 로드하는 방법


- 사이즈가 큰 이미지를 로드할때는 메모리에 부담이 발생합니다. 따라서 화면크기보다 큰 사이즈의 이미지는 아래와 같이 로드하는게 메모리에 부담이 적게됩니다.


로드하려는 비트맵 이미지의 정보 읽기

BitmapFactory.Options options = new BitmapFactory.Options();

// 이미지는 로드 하지 않고 out~~(outHeight, outWidth) 으로 시작되는 속성 정보만 읽는다., 메모리에 부담이 적게 된다.

// true 로 설정되어 있을 경우 decode 시에 null 을 리턴한다. 로드된 이미지가 없기 때문에

options.inJustDecodeBounds = true; 

BitmapFactory.decodeResource( getResources(), R.id.myimage, options);

int imageHeight = options.outHeight;

int imageWidth = options.outWidth;

String imageType = options.outMimeType;



로드하려는 이미지가 실제 필요한 사이즈보다 큰지 체크하는 메소드

실제 필요한 사이즈로 이미지를 조절하기 위해 체크하는 메소드

public static int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight){

final int height = options.outHeight;

final int width = options.outWidth;

int inSampleSize = 1;

if( height > reqHeight || width > reqWidth){

final int heightRatio = Math.round((float)height / (float)reqHeight);

final int widthRatio = Math.round((float)width / (float)reqWidth);

inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

}

return inSampleSize;

}


위의 calculateInSampleSize 메소드를 사용하여 이미지 로드하기

public static Bitmap decodeSampleBitmapFromResource( Resources res, int resId, int reqWidth, int reqHeight){

final BitmapFactory.Options options = new BitmapFactory.Options();

options.inJustDecodeBounds = true;

BitmapFactory.decodeResource( res, resId, options);

options.inSampleSize = calculateInSampleSize( options, reqWidth, reqHeight);

// 로드하기 위해서는 위에서 true 로 설정했던 inJustDecodeBounds 의 값을 false 로 설정합니다. 

options.inJustDecodeBounds = false;

return BitmapFactory.decodeResource( res, resId, options);

}



: