Kamel 是一个为 Compose Multiplatform 设计的异步媒体加载库。它提供了一种简单、可定制且高效的方式来加载、缓存、解码和显示应用程序中的图像。默认情况下,它使用 Ktor 客户端加载资源。
Kamel 已发布在 Maven Central 上:
repositories { mavenCentral() // ... }
将依赖项添加到公共源集:
kotlin { sourceSets { commonMain { dependencies { implementation("media.kamel:kamel-image:0.9.5") // ... } } } }
将依赖项添加到依赖项块:
dependencies { implementation("media.kamel:kamel-image:0.9.5") // ... }
请确保为您的平台添加 Ktor HttpClient 引擎的依赖项,使用这个链接。
要异步加载图像,您可以使用 asyncPainterResource 可组合函数,它可以从不同的数据源加载图像:
// 字符串 asyncPainterResource(data = "https://www.example.com/image.jpg") // Ktor Url asyncPainterResource(data = Url("https://www.example.com/image.jpg")) // URI asyncPainterResource(data = URI("https://www.example.com/image.png")) // 文件(JVM,Native) asyncPainterResource(data = File("/path/to/image.png")) // 文件(JS) asyncPainterResource(data = File(org.w3c.files.File(arrayOf(blob), "/path/to/image.png"))) // URL asyncPainterResource(data = URL("https://www.example.com/image.jpg")) // 以及更多...
asyncPainterResource 可用于加载 SVG、XML、JPEG 和 PNG 格式的图像,具体取决于平台实现。
asyncPainterResource 返回一个 Resource<Painter> 对象,可以使用 KamelImage 可组合函数来显示图像。
由于 Android 和桌面之间没有共享的资源系统,某些实现(例如获取器和映射器)仅适用于特定平台:
要从桌面应用程序资源加载图像文件,您必须将 resourcesFetcher 添加到 KamelConfig 中:
val desktopConfig = KamelConfig { takeFrom(KamelConfig.Default) // 仅在桌面上可用 resourcesFetcher() // 仅在桌面上可用 // 一个替代的 svg 解码器 batikSvgDecoder() }
假设项目的 /resources 目录中有一个 image.png 文件:
CompositionLocalProvider(LocalKamelConfig provides desktopConfig) { asyncPainterResource("image.png") }
要从 Android 应用程序资源加载图像文件,您必须将 resourcesFetcher 和 resourcesIdMapper 添加到 KamelConfig 中:
val context: Context = LocalContext.current val androidConfig = KamelConfig { takeFrom(KamelConfig.Default) // 仅在 Android 上可用 resourcesFetcher(context) // 仅在 Android 上可用 resourcesIdMapper(context) }
假设项目的 /res/raw 目录中有一个 image.png 文件:
CompositionLocalProvider(LocalKamelConfig provides androidConfig) { asyncPainterResource(R.raw.image) }
asyncPainterResource 支持使用尾随 lambda 进行配置:
val painterResource: Resource<Painter> = asyncPainterResource("https://www.example.com/image.jpg") { // 加载图像时使用的 CoroutineContext coroutineContext = Job() + Dispatcher.IO // 自定义 HTTP 请求 requestBuilder { // this: HttpRequestBuilder header("Key", "Value") parameter("Key", "Value") cacheControl(CacheControl.MAX_AGE) } }
KamelImage 是一个可组合函数,它接受一个 Resource<Painter> 对象,显示它并提供额外的功能:
KamelImage( resource = painterResource, contentDescription = "Profile", )
KamelImage 还可以用于通过 onFailure 获取 exception,
并使用 onLoading 参数的 progress,根据情况显示 snackbar 或进度指示器:
val coroutineScope = rememberCoroutineScope() val snackbarHostState = remember { SnackbarHostState() } Box { KamelImage( resource = painterResource, contentDescription = "个人资料", onLoading = { progress -> CircularProgressIndicator(progress) }, onFailure = { exception -> coroutineScope.launch { snackbarHostState.showSnackbar( message = exception.message.toString(), actionLabel = "隐藏", duration = SnackbarDuration.Short ) } } ) SnackbarHost(hostState = snackbarHostState, modifier = Modifier.padding(16.dp)) }
你也可以使用简单的 when 表达式提供自己的自定义实现:
when (val resource = asyncPainterResource("https://www.example.com/image.jpg")) { is Resource.Loading -> { Text("加载中...") } is Resource.Success -> { val painter: Painter = resource.value Image(painter, contentDescription = "个人资料") } is Resource.Failure -> { log(resource.exception) val fallbackPainter = painterResource("/path/to/fallbackImage.jpg") Image(fallbackPainter, contentDescription = "个人资料") } }
你可以通过 animationSpec 参数启用、禁用或自定义交叉淡入淡出(渐入)动画。将 animationSpec 设置为 null 将禁用动画:
KamelImage( resource = imageResource, contentDescription = "个人资料", // 默认为 null animationSpec = tween(), )
默认实现是 KamelConfig.Default。如果你希望配置它,可以按以下方式进行:
val customKamelConfig = KamelConfig { // 如果需要,复制默认实现 takeFrom(KamelConfig.Default) // 设置要缓存的图像数量 imageBitmapCacheSize = DefaultCacheSize // 添加 ImageBitmapDecoder imageBitmapDecoder() // 添加 ImageVectorDecoder (XML) imageVectorDecoder() // 添加 SvgDecoder (SVG) svgDecoder() // 添加 FileFetcher fileFetcher() // 配置 Ktor HttpClient httpFetcher { // httpCache 在 kamel-core 中定义,配置 ktor 客户端 // 安装 HttpCache 功能,使用 Kamel 提供的实现。 // 可以以字节为单位定义缓存大小。 httpCache(10 * 1024 * 1024 /* 10 MiB */) defaultRequest { url("https://www.example.com/") cacheControl(CacheControl.MaxAge(maxAgeSeconds = 10000)) } install(HttpRequestRetry) { maxRetries = 3 retryIf { httpRequest, httpResponse -> !httpResponse.status.isSuccess() } } // 需要添加 "io.ktor:ktor-client-logging:$ktor_version" Logging { level = LogLevel.INFO logger = Logger.SIMPLE } } // 更多可用功能。 }
Kamel 提供了一个通用的 Cache<K,V> 接口,默认实现使用基于 LinkedHashMap 的 LRU 内存缓存机制。你可以为每种类型提供要缓存的条目数,如下所示:
KamelConfig { // 默认为 100 imageBitmapCacheSize = 500 // 默认为 100 imageVectorCacheSize = 300 // 默认为 100 svgCacheSize = 200 }
Kamel 可以通过 实现 ktor 的 CacheStorage 功能为图像创建持久磁盘缓存。默认配置 KamelConfig.Default 安装此功能,磁盘缓存大小为 10 MiB。底层磁盘缓存基于 coil 的多平台 DiskLruCache 实现。
KamelConfig { httpFetcher { // 缓存大小可以以字节为单位定义。或者可以使用 DefaultHttpCacheSize(10 MiB)。 httpCache(DefaultHttpCacheSize) } }
你可以使用 LocalKamelConfig 应用自定义配置:
CompositionLocalProvider(LocalKamelConfig provides customKamelConfig) { asyncPainterResource("image.jpg") }
欢迎随时贡献!如果你想贡献,请随时创建 PR 或开启 issue。
Copyright 2021 Ali Albaali
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


职场AI,就用扣子
AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!


多风格AI绘画神器
堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。


零代码AI应用开发平台
零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5网页应用,无 需编写代码。


免费创建高清无水印Sora视频
Vora是一个免费创建高清无水印Sora视频的AI工具


最适合小白的AI自动化工作流平台
无需编码,轻松生成可复用、可变现的AI自动化工作流

大模型驱动的Excel数据处理工具
基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。


AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae 具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。


AI论文写作指导平台
AIWritePaper论文写作是一站 式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

