How to load remote SVG image using Coil in Jetpack Compose
Asked Answered
B

3

23

I'm failing to load this image in Image using Coil in Jetpack Compose

Breland answered 30/9, 2021 at 8:16 Comment(0)
D
29

Coil doesn't support SVG by default.

According to documentation, you need to:

  1. Add following dependency:

    implementation("io.coil-kt:coil-svg:$coil_version")
    
  2. Set SvgDecoder as decoder:

    Coil 2.0.0 version:

    AsyncImage(
        model = ImageRequest.Builder(LocalContext.current)
            .data(svgImageUrl)
            .decoderFactory(SvgDecoder.Factory())
            .build(),
        contentDescription = null
    )
    

    Coil 1.4.0 version:

    Image(
        rememberImagePainter(
            data = svgImageUrl,
            builder = {
                decoder(SvgDecoder(LocalContext.current))
            }
        ),
        contentDescription = null
    )
    

p.s. note that if you set the decoder this way, Coil will not be able to work with non-SVG images in this painter, so if you want some general solution, you should check the url extension and add the decoder accordingly.

Doner answered 30/9, 2021 at 9:18 Comment(0)
F
7

I was working on Jetpack Compose app and the urls I received from a remote API contained both .png/jpeg and .svg file extensions.

I added dependencies for both Coil Compose and SVG flavors for Coil Version 2.0.0 which is the latest version as of January 2023.

// Coil
implementation("io.coil-kt:coil-compose:2.2.2")
implementation("io.coil-kt:coil-svg:2.2.2")

I then chained decoderFactory(SvgDecoder.Factory()) to Image.Request builder.

val painter = rememberAsyncImagePainter(
                model = ImageRequest.Builder(context = LocalContext.current)
                    .data(urlPng or urlSvg)
                    .decoderFactory(SvgDecoder.Factory())
                    .error(R.drawable.empty_flag)
                    .placeholder(R.drawable.empty_logo)
                    .build()
            )

            Image(painter = painter, contentDescription = null)
            

The updated .components { add(SvgDecoder.Factory())} call mentioned by @jendress was not resolved in my case and so I went with decoderFactory().

Both urls with .png/.jpeg and .svg worked well and rendered the correct image without errors.

Forepaw answered 2/1, 2023 at 10:37 Comment(0)
F
6

The syntax for adding a new decoder has changed a bit from 1.4.0 to 2.x.x.

val imageLoader = ImageLoader.Builder(context)
.components {
    add(SvgDecoder.Factory())
}
.build()

You can find the latest syntax here: https://coil-kt.github.io/coil/svgs/

Franck answered 5/4, 2022 at 14:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.