민프

[Android] Bitmap 이미지의 크기 조정하기 본문

[Android]

[Android] Bitmap 이미지의 크기 조정하기

민프야 2021. 7. 1. 19:19
public Bitmap resizeBitmapImageFn(Bitmap bmpSource, int maxResolution){

int iWidth = bmpSource.getWidth(); //비트맵이미지의 넓이
int iHeight = bmpSource.getHeight(); //비트맵이미지의 높이
int newWidth = iWidth ; //새로운 비트맵 이미지의 넓이
int newHeight = iHeight ;//새로운 비트맵 이미지의 높이

float rate = 0.0f;



//이미지의 가로 세로 비율에 맞게 조절
if(iWidth > iHeight ){
if(maxResolution < iWidth ){
rate = maxResolution / (float) iWidth ;

newHeight = (int) (iHeight * rate);

newWidth = maxResolution;

}

}else{

if(maxResolution < iHeight ){

rate = maxResolution / (float) iHeight ;

newWidth = (int) (iWidth * rate);

newHeight = maxResolution;

}

}
Log.d(TAG+ " newWidth", String.valueOf(newWidth));
Log.d(TAG+ " newWidth", String.valueOf(newHeight));
Log.d(TAG+ " newWidth", String.valueOf(iWidth));
Log.d(TAG+ " newWidth", String.valueOf(iHeight));

Matrix matrix = new Matrix(); // bitmap의 스케일을 조정해줄 수 있는 Matrix 함수
// resize the bit map
matrix.postScale(newWidth, newHeight); // 새로운 사이즈에 맞게 이미지를 축소 확대
BitmapFactory.Options options = new BitmapFactory.Options(); // 이미지 옵션을 가지고 옴
options.inSampleSize=2; // 크기를 2배 축소시켜줌
options.inJustDecodeBounds = true; //이미지를 decoding할때 이미지의 크기만을 먼저 불러와 OutofMemory Exception을 일으킬만한 큰 이미지를 불러오더라도 선처리를 가능하도록 해준다.
// recreate the new Bitmap

return Bitmap.createScaledBitmap(bmpSource, newWidth, newHeight, true);
}


BitmapFactory class는 여러가지 리소스로부터 Bitmap 이미지를 만들어내기 위한 여러 decoding 메소드를 제공한다.

이중 options.inJustDecodeBounds를 true로 설정하면 이미지를 decoding할때 이미지의 크기만을 먼저 불러와 OutofMemory Exception을 일으킬만한 큰 이미지를 불러오더라도 선처리를 가능하도록 해준다.

 

디코딩 시 inJustDecodeBounds 속성을 true로 설정하면 메모리 할당이 방지됩니다. 그리고 비트 맵 객체에 null이 반환되지만 outWidth, outHeight, outMimeType은 설정됩니다. 이 기법을 사용하면 비트맵을 생성(메모리 할당 포함)하기 전에 이미지 데이터의 크기와 유형을 읽을 수 있습니다.

https://developer.android.com/topic/performance/graphics/load-bitmap?hl=ko

Comments