땀이 삐질삐질 나는 개발 일기

Glide 4.x 버전 이상에서 Gif 및 이미지 다운받아 파일로 저장 본문

개발 Tip

Glide 4.x 버전 이상에서 Gif 및 이미지 다운받아 파일로 저장

삐질 2019. 10. 22. 21:19
안녕하세요. 삐질삐질 개발하는 개발자 삐질입니다.
  • 아래 로직들은 기본 전제조건으로 해당 퍼미션의 Grant가 선 조건입니다.
  • Internet , Read Storage , Write Strorage
  • 또한 이 모든 작업은 BackgroundThread에서 실행되어야 합니다.
 
파일 다운로드
 
public void loadFile() {
    try {
        //글라이드를 통해 파일 다운로드
        RequestManager requestManager = Glide.with(this);
        File file = requestManager.downloadOnly().load(url).submit().get();
        Log.e("파일사이즈", "" + file.length());
        saveFile(file);
 
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
 
파일 세이브
public void saveFile(File file) {
 
    File localFile = new File(Environment.getExternalStoragePublicDirectory(filePath) .getPath());
    if (!localFile.exists()) {// 디렉토리가 있는지 없는지 부터 체크
        localFile.mkdirs(); //없으면 생성
    }
    String filepath = Environment.getExternalStoragePublicDirectory(filePath).getPath() + System.currentTimeMillis() + ".gif";
    localFile = new File(filepath); // 만들고자 하는 파일패스 + 네임 객체 할당
 
    try {
 
        InputStream
                is = new FileInputStream(file);
 
        Log.d(TAG, "on do in background, url get input stream");
        BufferedInputStream bis = new BufferedInputStream(is);
        Log.d(TAG, "on do in background, create buffered input stream");
 
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Log.d(TAG, "on do in background, create buffered array output stream");
 
        byte[] img = new byte[1024];
 
        int current = 0;
 
        Log.d(TAG, "on do in background, write byte to baos");
        while ((current = bis.read()) != -1) {
            baos.write(current);
        }
 
 
        Log.d(TAG, "on do in background, done write");
 
        Log.d(TAG, "on do in background, create fos");
        FileOutputStream fos = new FileOutputStream(localFile);
        fos.write(baos.toByteArray());
 
        Log.d(TAG, "on do in background, write to fos");
        fos.flush();
 
        fos.close();
        is.close();
        Log.d(TAG, "on do in background, done write to fos");
        scanMedia(); //미디어 스캔을 해줘야 , 시스템에서 바로 반영됨
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
 
미디어 스캔
public void scanMedia(File file) {
    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    intent.setData(Uri.fromFile(file));
    sendBroadcast(intent);
}
 
 
안드로이드 초보 개발자를 위해 아래와 같은 카카오 오픈톡을 운영 중입니다

 

https://open.kakao.com/o/gn4xqQ6open.kakao.com/o/gH0XvThcopen.kakao.com/o/gH0XvThc

Comments