메뉴 건너뛰기

?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄


관련글은

이며, 관련글도 차례로 보는게 더 도움이 되실겁니다. 

기본적인 뼈대는 구글 블로그에 공개되어 있는 멀티 쓰레드를 이용한 이미지 다운로드 소스입니다. 
여기에 URL을 이용한 파일 캐싱 기능과 이미지 크기가 너무 커서 BitmapFactory에서 decoding 도중에
bitmap size exceeds VM budget 오류를 발생하며 종료되는 부분을 처리했습니다.


그리고, Bitmap 이미지를 파일로 저장하는 과정에서

bitmap.compress(CompressFormat.JPEG, 100, out);
bitmap.compress(CompressFormat.PNG, 100, out); 

2가지 옵션을 사용할 수 있는데

이미지를 JPEG로 압축할 경우, 특정 사진들에 대해서 화질이 너무 안 좋다는 단점이 있었고
이미지를 PNG로 압축할 경우에는 화질은 JPEG보다 우수하지만 압축하는데 시간과 리소스가
너무 오래걸린다는 단점이 있었습니다. (둘다 이미지를 압축하기 때문에 시간 및 리소스가 소비됩니다.)


그래서 그냥 네트워크로 받은 이미지를 원본 그대로 파일로 저장한다음, 그 파일에서 BitmapFactory.decodeFile을 
이용해서 불러오는 것으로 바꾸었습니다. 



다음은 파일에서 이미지를 bitmap size exceeds VM budget 오류를 발생시키지 않고 안전하게 불러오는
부분입니다. 

01.// File 에서 이미지를 불러올 때 안전하게 불러오기 위해서 만든 함수
02.// bitmap size exceeds VM budget 오류 방지용
03.Bitmap SafeDecodeBitmapFile(String strFilePath)
04.{
05.    File file = new File(strFilePath);
06.    if (file.exists() == false)
07.    {
08.        return null;
09.    }
10.     
11.    // 가로, 세로 최대 크기 (이보다 큰 이미지가 들어올 경우 크기를 줄인다.)
12.    final int IMAGE_MAX_SIZE    = GlobalConstants.getMaxImagePixelSize();   
13.    BitmapFactory.Options bfo   = new BitmapFactory.Options();
14.    bfo.inJustDecodeBounds      = true;
15.     
16.    BitmapFactory.decodeFile(strFilePath, bfo);
17.     
18.    if(bfo.outHeight * bfo.outWidth >= IMAGE_MAX_SIZE * IMAGE_MAX_SIZE)
19.    {
20.        bfo.inSampleSize = (int)Math.pow(2, (int)Math.round(Math.log(IMAGE_MAX_SIZE
21.                            / (double) Math.max(bfo.outHeight, bfo.outWidth)) / Math.log(0.5)));
22.    }
23.    bfo.inJustDecodeBounds = false;
24.    bfo.inPurgeable = true;
25.    bfo.inDither = true;
26.    
27.    final Bitmap bitmap = BitmapFactory.decodeFile(strFilePath, bfo);
28.     
29.    return bitmap;
30.}




그리고 이미지를 네트워크에서 다운로드해서 파일로 저장하는 함수입니다.

001.Bitmap downloadBitmap(String strImageURL)
002.{
003.    final HttpClient client         = (mode == Mode.NO_ASYNC_TASK) ?
004.            new DefaultHttpClient() : AndroidHttpClient.newInstance("Android");
005.             
006.    final HttpGet getRequest        = new HttpGet(strImageURL);
007.    // 가로, 세로 최대 크기 (이보다 큰 이미지가 들어올 경우 크기를 줄인다.)
008.    final int IMAGE_MAX_SIZE        = GlobalConstants.getMaxImagePixelSize();
009.    // FileCache를 위한 이미지 파일명(URL Encoding)
010.    final String strImageFilePath   = GlobalConstants.GetImageFileCachePath()
011.                                            + URLEncoder.encode(strImageURL);  
012.     
013.    try
014.    {
015.        // FileCache를 먼저 확인한 다음 원하는 이미지가 없으면 다운 받는다.
016.        if (bUseFileCache == true)
017.        {
018.            //Bitmap bitmap = BitmapFactory.decodeFile(strImageFilePath);
019.            Bitmap bitmap = SafeDecodeBitmapFile(strImageFilePath);
020.             
021.            if (bitmap != null)
022.            {
023.                return bitmap;
024.            }
025.        }
026.         
027.        HttpResponse response = client.execute(getRequest);
028.        final int statusCode = response.getStatusLine().getStatusCode();
029.         
030.        if (statusCode != HttpStatus.SC_OK)
031.        {
032.            return null;
033.        }
034. 
035.        final HttpEntity entity = response.getEntity();
036.         
037.        if (entity != null)
038.        {
039.            InputStream inputStream = null;
040.             
041.            try
042.            {
043.                inputStream = entity.getContent();
044. 
045.                if (bUseFileCache == true)
046.                {
047.                    // FlieCache 파일 개수 관리
048.                    ManageFileCache(GlobalConstants.GetImageFileCachePath());
049.                     
050.                    // Download한 이미지를 파일로 저장
051.                    File file = new File(strImageFilePath);
052.                    FileOutputStream fileOutput = new FileOutputStream(file); 
053.                     
054.                    FlushedInputStream fis = new FlushedInputStream(inputStream);
055.                    byte[] buffer = new byte[1024];  
056.                    int bufferLength = 0;
057.                     
058.                    try
059.                    {
060.                        while ((bufferLength = fis.read(buffer)) > 0)
061.                        {  
062.                            fileOutput.write(buffer, 0, bufferLength);
063.                        }
064.                         
065.                        fileOutput.flush();
066.                        fileOutput.close();
067.                         
068.                        return SafeDecodeBitmapFile(strImageFilePath);
069.                    }
070.                    catch(IOException e)
071.                    {
072.                        e.printStackTrace();
073.                    }
074.                }
075.                else
076.                {
077.                    // FileCache를 사용하지 않을 때 네트워크로부터 이미지를 다운 받는 부분
078.                    BitmapFactory.Options bfo   = new BitmapFactory.Options();
079.                    bfo.inJustDecodeBounds      = true;
080.                     
081.                    BitmapFactory.decodeStream(new FlushedInputStream(inputStream), null, bfo);
082.                     
083.                    if(bfo.outHeight * bfo.outWidth >= IMAGE_MAX_SIZE * IMAGE_MAX_SIZE)
084.                    {
085.                        bfo.inSampleSize = (int)Math.pow(2, (int)Math.round(Math.log(IMAGE_MAX_SIZE
086.                                            / (double) Math.max(bfo.outHeight, bfo.outWidth))
087.                                            / Math.log(0.5)));
088.                    }
089.                    bfo.inJustDecodeBounds = false;
090.                     
091.                    response = client.execute(getRequest);
092.                    final int nRetryStatusCode = response.getStatusLine().getStatusCode();
093.                     
094.                    if (nRetryStatusCode != HttpStatus.SC_OK)
095.                    {
096.                        return null;
097.                    }
098.                     
099.                    final HttpEntity reEntity = response.getEntity();
100.                     
101.                    if (reEntity != null)
102.                    {
103.                        InputStream reInputStream = null;
104.                         
105.                        try
106.                        {
107.                            reInputStream = reEntity.getContent();
108.                            final Bitmap imgBitmap = BitmapFactory.decodeStream(
109.                                                new FlushedInputStream(reInputStream), null, bfo);
110.                             
111.                            return imgBitmap;
112.                        }
113.                        finally
114.                        {
115.                             if (reInputStream != null)
116.                             {
117.                                 reInputStream.close();
118.                             }
119.                              
120.                             reEntity.consumeContent();
121.                        }
122.                    }
123.                }
124.            }
125.            finally
126.            {
127.                if (inputStream != null)
128.                {
129.                    inputStream.close();
130.                }
131.                 
132.                entity.consumeContent();
133.            }
134.        }
135.    }
136.    catch (IOException e)
137.    {
138.        getRequest.abort();
139.    }
140.    catch (IllegalStateException e)
141.    {
142.        getRequest.abort();
143.    }
144.    catch (Exception e)
145.    {
146.        getRequest.abort();
147.    }
148.    finally
149.    {
150.        if ((client instanceof AndroidHttpClient))
151.        {
152.            ((AndroidHttpClient)client).close();
153.        }
154.    }
155.     
156.    return null;
157.}

 


그리고 마지막으로 File Cache로 지정한 폴더에서 파일 개수가 일정 개수가 넘어갈 경우 
가장 오래된 파일부터 지우는 함수입니다.

01.private void ManageFileCache(String strFolderPath)
02.{
03.    long nLastModifiedDate = 0;
04.    File targetFile = null;
05.     
06.    while(true)
07.    {
08.        File[] arrFiles = new File(strFolderPath).listFiles();
09.         
10.        if (arrFiles.length < GlobalConstants.GetImageFileCacheSize())
11.        {
12.            break;
13.        }
14.         
15.        for (File file : arrFiles)
16.        {
17.            if (nLastModifiedDate < file.lastModified())
18.            {
19.                nLastModifiedDate = file.lastModified();
20.                targetFile = file;
21.            }
22.        }
23.         
24.        if (targetFile != null)
25.        {
26.            targetFile.delete();
27.        }
28.    }
29.}

List of Articles
번호 제목 날짜 조회 수
117 사용자 정의 팝업창 띄우기 2015.07.16 6337
116 HTML5 Form 공부하기 -2- file 2014.09.04 6329
115 WebView 줌 컨트롤러 가리기 2014.08.28 6316
114 HTML5로 나만의 비디오 플레이어 스킨 만들기 -2- JavaScript file 2014.09.04 6312
113 전화 인텐트와 나의 전화 번호가져오기 2014.08.28 6312
112 HTML5로 나만의 비디오 플레이어 스킨 만들기 -3- JavaScript file 2014.09.04 6288
111 푸쉬 알림 기능. GCM (Google Cloud Messaging) 사용하기 (3) file 2015.07.16 6267
110 Effects - Stop() 메서드 (애니메이션 효과 멈추기) file 2014.10.16 6225
109 클래스나눠서 xml 파싱과 FTP를이용하여 안드로이드에서 활용하기 2014.08.28 6180
» 네트워크를 통해 받은 이미지를 파일로 저장하고, 크기 조절해서 불러오기 2015.07.16 6155
107 Effects - FadeIn() / FadeOut() 메서드 (서서히 보이기 및 숨기기) file 2014.10.16 6069
106 HTML5로 게임 만들기 워밍업 file 2014.09.04 6063
105 Effects - SlideUp() 메서드 (슬라이드업) file 2014.10.16 5999
104 안드로이드 이미지 효율적으로 회전 해보기 2014.08.28 5995
103 Effects - Show() / Hide() 메서드 (보이기 및 숨기기) file 2014.10.16 5957
102 HTML5 Better semantic tags file 2014.09.04 5952
101 HTML5 Form 공부하기 -1- file 2014.09.04 5841
100 Events - Unbind() 메서드 (이벤트 처리기 해제) file 2014.10.16 5749
99 HTML5 시작하기 file 2014.09.04 5660
98 HTML5 Web Storage -01- file 2014.09.04 5587
Board Pagination Prev 1 ... 3 4 5 6 7 8 9 10 11 12 13 Next
/ 13

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved