개발을 하던 중 이미지를 캐싱해야되는 경우가 생겼다..비트맵으로 변환하여 Glide를 통해 이미지를 띠어주었는데, 내가 하려는 방식과 glide의 캐싱방식은 맞지 못해서 다른 방식을 써보기로 하였다.
내부저장소에 직접 파일을 저장하고 캐싱하는 방식을 사용했다.
나는 RecyclerView를 통해 이미지를 많이 보이는 작업을 진행하였고, 해당 recyclerView의 이미지를 가져오는 Fragment에서 해당 코드를 구현하였다.
Cache의 기본 동작 방식
1. 만약 Cache에 Key에 해당하는 Value가 있다면, 해당 Value를 받아와 사용한다.
2. Cache에 Key에 해당하는 Value가 없다면, Value를 저장하고 있는 곳(서버)에서 받아와 사용하고, 다음 번의 사용을 위해 Cache에 저장한다.
위와 같은 방식을 구현하기 위해서 Cache에서 파일이 있는지 확인하는 함수와, 저장하는 함수가 필요하다.
private Bitmap getBitmapFromCache(String key) {
String found = null;
Bitmap bitmap = null;
File file = new File(getContext().getCacheDir().toString());
File[] files = file.listFiles();
for (File tempFile : files) {
if (tempFile.getName().contains(key)) {
found = (tempFile.getName());
String path = getContext().getCacheDir() + "/" + found;
bitmap = BitmapFactory.decodeFile(path);
}
}
return bitmap;
}
getBitmapFromCacheDir에서는 cacheDir에서 key를 통해 파일을 찾는다. 만약 파일이 있다면 file을 decode해서 return 해주고, 없다면 null 값을 return 해줄 것이다!
private void saveBitmapToCache(Bitmap bitmap, String name) {
File storage = (getContext()).getCacheDir();
String fileName = name;
try {
File tempFile = new File(storage, fileName);
tempFile.createNewFile();
FileOutputStream out = new FileOutputStream(tempFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
} catch (FileNotFoundException e) {
Log.e(TAG, "FileNotFoundException : " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException : " + e.getMessage());
}
}
saveBitmapToJpeg에서는 Cache에 저장해주는 동작을 수행한다.
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
위의 문장에서 "100"은 원본 화질 그대로 사진을 압축하는 것이다. 속도를 더욱 빠르게 하고 싶다면 화질을 저하시키는 것이 좋다.
위 두 함수만 있다면 기본적인 구현은 가능하다! 아래와 같은 방식으로 사용한다면 내부저장소를 통해 캐시를 사용하는 것이 가능해진다 후후ㅠㅠ
Bitmap b = getBitmapFromCache(key);
if (bit != null) {
Glide.with(this).load(b).diskCacheStrategy(DiskCacheStrategy.NONE).circleCrop().into(imageView);
} else {
//...server에서 이미지 불러오기
Bitmap b = getImageFromserver();
if (b != null) {
Glide.with(this).load(b).diskCacheStrategy(DiskCacheStrategy.NONE).circleCrop().into(imageView);
saveBitmapToCache(b, key);
}
}
다음 시간엔 서버에서 사진을 가져오는 방식을 MainThread를 사용하는 방식이 아닌 Back에서 돌려 가져오는 방식을 사용해보려고 한다.
!! 안드로이드 개발 화이팅..😱
참고 사이트
kimdohyeong.gitbooks.io/android_official_training_kr/content/Caching_Bitmaps.html
'Front-End 🧚🏻 > Android' 카테고리의 다른 글
[안드로이드(Android)-JAVA] Material Design Icons 적용 방법과 색상 변경 (1) | 2020.12.02 |
---|---|
[안드로이드(Android)-JAVA]LiveData 사용하여 실시간으로 데이터 변경하기 (0) | 2020.11.24 |
댓글