상세 컨텐츠

본문 제목

[TIP] ImageView 의 setImageURI 에서 OOM(OutOfMemory) 에러발생시.

프로그램개발/안드로이드

by fsteam 2013. 7. 10. 13:54

본문

 File picture = new File("path_to_image");
        if (picture.exists()) {
            ImageView imageView = (ImageView)findViewById(R.id.imageView);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 2;
            Bitmap myBitmap = BitmapFactory.decodeFile(picture.getAbsolutePath(), options);
            imageView.setImageBitmap(myBitmap);
        }


안드로이드에서 그리드나 리스트를 이용해서 여러개의 이미지를 로딩해서 보여주는 경우..

(특히나 이미지의 사이즈가 큰 경우)

스크롤을 통해서 이미지를 점점 많이 열게 되면 OOM(Out Of Memory) 오류를 만날 수 있다.


이에 대해서 여러가지 자료를 찾아 봤는데, 주로 비트맵을 만든 후 이것을 리사이클해서 사용하라는 말들이 많았다.

그런데 이걸로도 해결하지 못해서 ㅠ.ㅠ


결국 해결한 방식은 비트맵 샘플링 하는 방식으로 처리했다.


위처럼 프리뷰에서 이미지 보여주기 전에 BitmapFactory 옵션을 지정하는 방식으로 (샘플링 사이즈 변경) 처리 가능하다.


public int inSampleSize

Added in API level 1

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value <= 1 is treated the same as 1. Note: the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2.


관련글 더보기