13
7

Android Glideを使用したimageダウンロードと表示(kotlin)

Last updated at Posted at 2024-03-03

この記事でわかること

  • 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は画像表示に失敗した際に実行されます。

画像ダウンロードのデバッグ・確認方法

  1. View > Tool Windows > Device Explorer をクリックします。
    image.png
  2. 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/

13
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
7