この記事でわかること
- Glideを使用した画像のダウンロード
- 画像ダウンロードのデバッグ・確認方法
- ダウンロードした画像の表示
Glideを使用した画像のダウンロード
引数で保存先のディレクトリとファイル名を指定できるようにしています。ディレクトリを深く作成することも可能です。
fun save(imageUrl: String, directoryName: String, fileName: String) {
Glide.with(context)
.asBitmap()
.load(imageUrl)
.into(object: CustomTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
val directory = File(context.filesDir, directoryName).apply {
if (!exists()) mkdirs()
}
val file = File(directory, fileName)
val quality = 100
FileOutputStream(file).use { out ->
resource.compress(Bitmap.CompressFormat.PNG, quality, out)
Log.i(TAG, "image saved to internal storage path=${file.absolutePath}")
}
}
override fun onLoadCleared(placeholder: Drawable?) {
}
})
}
resource.compress(Bitmap.CompressFormat.PNG, quality, out)
ここでは、保存時のファイル形式と画質と保存先を渡しています。
ファイル形式は、JPEG, PNG, (WEBP), WEBP_LOSSY, WEBP_LOSSLESSが指定できます。
use
関数を使用して、エラーが出た時にリソースを閉じています。今回の開発で初めて知りましたが、主にファイル書き込みやdatabase接続などのCloseableリソースを扱う際に使用されます。
onLoadCleared
は画像表示に失敗した際に実行されます。
画像ダウンロードのデバッグ・確認方法
- View > Tool Windows > Device Explorer をクリックします。
- Device Explorerから
data/data/[Packege Name]/files/[directory name]/
を確認するとファイルが保存される
ダウンロードした画像の表示
@Composable
fun OfflineImage(
filePath: String,
modifier: Modifier = Modifier,
contentScale: ContentScale = ContentScale.Fit,
context: Context = LocalContext.current,
) {
val imageBitmap: ImageBitmap? by produceState<ImageBitmap?>(initialValue = null, filePath) {
val file = File(context.filesDir, filePath)
value = if (file.exists()) {
val bitmap = BitmapFactory.decodeFile(file.absolutePath)
bitmap.asImageBitmap()
} else {
null
}
}
imageBitmap?.let {
Image(
bitmap = it,
contentDescription = null,
contentScale = contentScale,
modifier = modifier
)
}
}
produceState
を使用して非同期でbitmapを取得してimageBitmap(value)
にセットして画像を表示しています。
参考リンク
https://developer.android.com/jetpack/compose/side-effects#producestate
https://bumptech.github.io/glide/