Support for data://
URIs
#764
Replies: 3 comments
-
Here’s a custom internal class Base64ImageFetcher(private val context: Context) : Fetcher<Uri> {
override fun handles(data: Uri) = data.scheme == "data"
override suspend fun fetch(pool: BitmapPool, data: Uri, size: Size, options: Options) = DrawableResult(
drawable = BitmapDrawable(context.resources, base64Decode(data.toString())),
isSampled = false,
dataSource = DataSource.MEMORY
)
override fun key(data: Uri) = data.toString()
companion object {
private fun base64Decode(dataURI: String): Bitmap? {
val decodedBytes = Base64.decode(dataURI.substringAfter(','), DEFAULT)
return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size)
}
}
} Use it as: ImageLoader.Builder(context)
.componentRegistry {
add(Base64ImageFetcher(context))
}
.build() |
Beta Was this translation helpful? Give feedback.
-
Here's a custom Fetcher for Data URIs that works on version class Base64ImageFetcher(
private val context: Context,
private val data: Uri,
) : Fetcher {
override suspend fun fetch() = DrawableResult(
drawable = BitmapDrawable(
context.resources,
base64Decode(data.toString())
),
isSampled = false,
dataSource = DataSource.MEMORY
)
companion object {
private fun base64Decode(dataURI: String): Bitmap? {
val decodedBytes = Base64.decode(dataURI.substringAfter(','), Base64.DEFAULT)
return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size)
}
}
class Factory : Fetcher.Factory<Uri> {
override fun create(data: Uri, options: Options, imageLoader: ImageLoader): Fetcher {
return Base64ImageFetcher(options.context, data)
}
}
}
|
Beta Was this translation helpful? Give feedback.
-
When my company went to implement this, we observed data: URIs are supported natively by web browsers (obviously), but also by the popular sd_webimage loader on iOS. Coil was the only one that didn't already work. Makes sense to include the above^ in the repo (but, it could be better. instead of returning bitmap, it should pass the bytes to the decoders) Anyway, thanks for the sample code :) |
Beta Was this translation helpful? Give feedback.
-
I looked through the issues, trying to see if there’s a plan to support Data URIs, but didn’t find anything concrete.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
Beta Was this translation helpful? Give feedback.
All reactions