skydoves / landscapist

🌻 A pluggable, highly optimized Jetpack Compose and Kotlin Multiplatform image loading library that fetches and displays network images with Glide, Coil, and Fresco.
https://skydoves.github.io/landscapist/
Apache License 2.0
2.12k stars 114 forks source link

Generate bitmap from a url with coil3 #504

Closed ArleyPereira closed 3 months ago

ArleyPereira commented 3 months ago

I need to generate a bitmap from an image URL. I'm using coil3 import. I couldn't find any examples in the documentation.

Import: com.github.skydoves:landscapist-coil3 Version: 2.3.3

agp = "8.3.2" kotlin = "2.0.0" composeBom = "2024.06.00"

skydoves commented 3 months ago

You can get a bitmap from the success state like the example below:

  var coilImageState by rememberCoilImageState()

  val state = coilImageState
  if (state is CoilImageState.Success) {
    val bitmap = state.imageBitmap?.asAndroidBitmap()
      ..
  }

  CoilImage(
    imageModel = { poster.image },
    onImageStateChanged = { coilImageState = it },
  )
ArleyPereira commented 3 months ago

Thank you very much for your example. My problem is that I need to generate a bitmap from an image url that will be used in setLargeIcon() of the NotificationCompat class.

Screenshot at Jun 21 09-26-02

I managed to get the bitmap from an image url using the code below. Maybe this library offers some solution for this case?

suspend fun getBitmapFromUrl(url: String?): Bitmap? {
    return withContext(Dispatchers.IO) {
        var bitmap: Bitmap? = null
        var connection: HttpURLConnection? = null
        var inputStream: InputStream? = null

        try {
            val imageUrl = URL(url)
            connection = imageUrl.openConnection() as HttpURLConnection
            connection.doInput = true
            connection.connect()

            val responseCode = connection.responseCode
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inputStream = connection.inputStream
                bitmap = BitmapFactory.decodeStream(inputStream)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            inputStream?.close()
            connection?.disconnect()
        }

        bitmap
    }
}