55 lines
No EOL
1.5 KiB
Kotlin
55 lines
No EOL
1.5 KiB
Kotlin
package com.pixelized.biblib.utils
|
|
|
|
import android.content.Context
|
|
import android.graphics.Bitmap
|
|
import android.graphics.BitmapFactory
|
|
import android.util.Log
|
|
import kotlinx.coroutines.Dispatchers
|
|
import kotlinx.coroutines.withContext
|
|
import java.io.File
|
|
import java.io.IOException
|
|
import java.net.URL
|
|
import javax.inject.Inject
|
|
|
|
class BitmapCache @Inject constructor(context: Context) {
|
|
private var cache: File? = context.cacheDir
|
|
|
|
fun writeToDisk(url: URL, bitmap: Bitmap) {
|
|
val file = file(url)
|
|
try {
|
|
file.mkdirs()
|
|
file.delete()
|
|
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, file.outputStream())
|
|
} catch (e: Exception) {
|
|
Log.e("BitmapCache", "bitmap?.compress() FAILED !", e)
|
|
}
|
|
}
|
|
|
|
fun readFromDisk(url: URL): Bitmap? {
|
|
val file = file(url)
|
|
return try {
|
|
BitmapFactory.decodeStream(file.inputStream())
|
|
} catch (e: IOException) {
|
|
null
|
|
}
|
|
}
|
|
|
|
fun exist(url: URL): Boolean {
|
|
val file = file(url)
|
|
return file.exists()
|
|
}
|
|
|
|
suspend fun download(url: URL): Bitmap? {
|
|
Log.v("BitmapCache","download: $url")
|
|
return withContext(Dispatchers.IO) {
|
|
try {
|
|
BitmapFactory.decodeStream(url.openStream())
|
|
} catch (e: IOException) {
|
|
Log.e("BitmapCache", "BitmapFactory.decodeStream(URL) FAILED !", e)
|
|
null
|
|
}
|
|
}
|
|
}
|
|
|
|
private fun file(url: URL): File = File(cache?.absolutePath + url.file)
|
|
} |