### Install sketch-video Modules Source: https://github.com/panpf/sketch/blob/main/docs/video_frame.md Add the sketch-video or sketch-video-ffmpeg dependency to your project's build.gradle file. These components support automatic registration. ```kotlin implementation("io.github.panpf.sketch4:sketch-video:${LAST_VERSION}") // or implementation("io.github.panpf.sketch4:sketch-video-ffmpeg:${LAST_VERSION}") ``` -------------------------------- ### Create Simple ImageRequest Source: https://github.com/panpf/sketch/blob/main/docs/getting_started.md Create a basic ImageRequest with a specified size limit. This is the starting point for most image loading tasks. ```kotlin val request = ImageRequest(context, "https://www.example.com/image.jpg") { size(300, 300) // There is a lot more... } ``` -------------------------------- ### Load Installed App Icon Source: https://github.com/panpf/sketch/blob/main/docs/apk_app_icon.md Use the newAppIconUri() function to create a dedicated URI for an installed app's icon, specifying the package name and version code. This ensures correct icon caching and refreshing. ```kotlin // app.icon://com.github.panpf.sketch.sample/1 val appIconUri = newAppIconUri(packageName = "com.github.panpf.sketch.sample", versionCode = 1) sketch.enqueue(ImageRequest(context, uri = appIconUri)) ``` -------------------------------- ### Compose Multiplatform Dependencies Source: https://github.com/panpf/sketch/blob/main/README.md Import the core Sketch Compose module and the HTTP module for network image loading. Ensure you have the latest version installed. ```kotlin implementation("io.github.panpf.sketch4:sketch-compose:${LAST_VERSION}") implementation("io.github.panpf.sketch4:sketch-http:${LAST_VERSION}") ``` -------------------------------- ### Load Images from Local File Paths Source: https://github.com/panpf/sketch/blob/main/docs/fetcher.md Demonstrates loading images using various local file path formats, including absolute paths, URIs, and Windows-specific paths. These examples do not require additional modules. ```kotlin val imageUri1 = "file:///storage/emulated/0/Pictures/image.jpg" val imageUri2 = "file:/storage/emulated/0/Pictures/image.jpg" val imageUri3 = "/storage/emulated/0/Pictures/image.jpg" val imageUri4 = "D:\\images\\image.jpg" // Windows only val imageUri5 = "\\qnap\\photos\\image.jpg" // Windows network path only // compose AsyncImage( uri = imageUri, contentDescription = "photo" ) // android viewimageView.loadImage(imageUri) ``` -------------------------------- ### Configure iOS Photos Library Loading Source: https://github.com/panpf/sketch/blob/main/docs/fetcher.md Provides an example of configuring image loading from the iOS Photos Library, including options to prefer thumbnails and allow network access for iCloud images. ```kotlin val imageUri = newPhotosAssetUri("DB16113B-984A-4D12-B4D0-50FC46066781/L0/001") val request = ImageRequest(context, imageUri) { // Thumbnails are loaded first. The default value is false, which means the original image is loaded first. preferThumbnailForPhotosAsset(true) // Allow loading images from iCloud. The default value is false, which means loading images from iCloud is not allowed. allowNetworkAccessPhotosAsset(true) } AsyncImage( request = request, contentDescription = "photo" ) ``` -------------------------------- ### Install sketch-blurhash Component Source: https://github.com/panpf/sketch/blob/main/docs/blurhash.md Add the sketch-blurhash dependency to your project's build file. This module supports automatic component registration. ```kotlin implementation("io.github.panpf.sketch4:sketch-blurhash:${LAST_VERSION}") ``` -------------------------------- ### Install sketch-animated-gif Source: https://github.com/panpf/sketch/blob/main/docs/animated_image.md Add the `sketch-animated-gif` dependency to your project's build file to enable GIF loading. This component supports automatic registration. ```kotlin implementation("io.github.panpf.sketch4:sketch-animated-gif:${LAST_VERSION}") ``` -------------------------------- ### Install sketch-svg Component Source: https://github.com/panpf/sketch/blob/main/docs/svg.md Add the sketch-svg dependency to your project's build.gradle file to enable SVG support. Ensure you use the correct version matching your Sketch installation. ```kotlin implementation("io.github.panpf.sketch4:sketch-svg:${LAST_VERSION}") ``` -------------------------------- ### Add View Extension Dependency Source: https://github.com/panpf/sketch/blob/main/docs/mime_type_logo.md Install the Sketch View extension for displaying mime type logos. Ensure you use the latest version. ```kotlin implementation("io.github.panpf.sketch4:sketch-extensions-view:${LAST_VERSION}") ``` -------------------------------- ### Android View Dependencies Source: https://github.com/panpf/sketch/blob/main/README.md Import the core Sketch View module and the HTTP module for network image loading. Ensure you have the latest version installed. ```kotlin implementation("io.github.panpf.sketch4:sketch-view:${LAST_VERSION}") implementation("io.github.panpf.sketch4:sketch-http:${LAST_VERSION}") ``` -------------------------------- ### Install Sketch Extensions Core Source: https://github.com/panpf/sketch/blob/main/docs/save_cellular_traffic.md Add the sketch-extensions-core dependency to your project to use the cellular traffic saving feature. ```kotlin implementation("io.github.panpf.sketch4:sketch-extensions-core:${LAST_VERSION}") ``` -------------------------------- ### Get Download Cache Key from ImageResult Source: https://github.com/panpf/sketch/blob/main/docs/download_cache.md Shows how to retrieve the download cache key from a successful ImageResult after executing a request. ```kotlin // Get the download cache key from ImageResult val imageSuccess = sketch.execute(request) as ImageResult.Success imageSuccess.downloadCacheKey ``` -------------------------------- ### Add Compose Extension Dependency Source: https://github.com/panpf/sketch/blob/main/docs/mime_type_logo.md Install the Sketch Compose extension for displaying mime type logos. Ensure you use the latest version. ```kotlin implementation("io.github.panpf.sketch4:sketch-extensions-compose:${LAST_VERSION}") ``` -------------------------------- ### Load Image in Android View Source: https://github.com/panpf/sketch/blob/main/docs/getting_started.md Shows how to load images into an Android ImageView using Sketch's extension functions and ImageRequest. It includes examples for basic loading and loading with custom configurations like placeholders and error images. ```kotlin // val imageUri = "/sdcard/download/image.jpg" // val imageUri = "file:///android_asset/image.jpg" // val imageUri = "content://media/external/images/media/88484" val imageUri = "https://example.com/image.jpg" imageView.loadImage(imageUri) ``` ```kotlin val imageUri = "https://example.com/image.jpg" imageView.loadImage(imageUri) { placeholder(R.drawable.placeholder) error(R.drawable.error) crossfade() // There is a lot more... } ``` ```kotlin val request = ImageRequest(context, imageUri) { placeholder(R.drawable.placeholder) error(R.drawable.error) crossfade() target(imageView) // There is a lot more... } context.sketch.enqueue(request) ``` -------------------------------- ### Customize Sketch Log Output Source: https://github.com/panpf/sketch/blob/main/docs/log.md Implement a custom Logger.Pipeline to control how logs are output. This example shows a custom pipeline that prints logs to the console, including stack traces for errors. ```kotlin class MyPipeline : Logger.Pipeline { override fun log(level: Logger.Level, tag: String, msg: String, tr: Throwable?) { if (tr != null) { val trString = tr.stackTraceToString() println("$level. $tag. $msg. \n$trString") } else { println("$level. $tag. $msg") } } override fun flush() { } override fun toString(): String = "MyPipeline" } Sketch.Builder(context).apply { logger(pipeline = MyPipeline()) }.build() ``` -------------------------------- ### Read and Write to Memory Cache Source: https://github.com/panpf/sketch/blob/main/docs/memory_cache.md Demonstrates how to interact with the memory cache instance to put, get, check existence, and remove cached values. It's crucial to use `withLock` for thread safety. ```kotlin scope.launch { val memoryCache = sketch.memoryCache val memoryCacheKey = requestContext.memoryCacheKey memoryCache.withLock(memoryCacheKey) { // put val newBitmap: Bitmap = Bitmap.create(100, 100, Bitmap.Config.ARGB_8888) val newCacheValue = newBitmap.asImage().cacheValue()!! put(memoryCacheKey, newCacheValue) // exist val exist: Boolean = exist(memoryCacheKey) // get val cachedValue: MemoryCache.Value? = get(memoryCacheKey) val image: Image = cachedValue?.image // remove val clearedValue: MemoryCache.Value? = remove(memoryCacheKey) } // Clear all memoryCache.clear() // trim memoryCache.trim((memoryCache.maxSize * 0.5f).toLong()) } ``` -------------------------------- ### Initialize Sketch and Load Images Source: https://github.com/panpf/sketch/blob/main/docs/getting_started.md Create a Sketch instance and use it with AsyncImage for Compose or enqueue an ImageRequest for Views. ```kotlin val sketch = Sketch(context) // Compose AsyncImage( uri = "https://www.example.com/image.jpg", sketch = sketch, moidifier = Modifier.fillMaxSize(), contentDescription = "photo", ) // View val request = ImageRequest(imageView, uri = "https://www.example.com/image.jpg") sketch.enqueue(request) ``` -------------------------------- ### Initialize Sketch with Koin and Load Images Source: https://github.com/panpf/sketch/blob/main/docs/getting_started.md Configure Sketch as a singleton within Koin modules for dependency injection and then use it for image loading. ```kotlin // Initialize koin in the app's entry function or onCreate in the Application startKoin { modules( module { single { Sketch.Builder(get()).apply { logger(level = Logger.Level.Debug) // There is a lot more... }.build() } }) } // Get instances anywhere val sketch = KoinPlatform.getKoin().get() // Compose AsyncImage( uri = "https://www.example.com/image.jpg", moidifier = Modifier.fillMaxSize(), contentDescription = "photo", ) // View imageView.loadImage(uri = "https://www.example.com/image.jpg") // or ImageRequest(imageView, uri = "https://www.example.com/image.jpg").enqueue(request) ``` -------------------------------- ### Using AsyncImageState with AsyncImage Source: https://github.com/panpf/sketch/blob/main/docs/compose.md Demonstrates how to initialize AsyncImageState and use it with AsyncImage to display an image. It also shows how to access the result, load state, progress, and painter state, and how to reload the image using the restart() method. ```kotlin val state = rememberAsyncImageState() AsyncImage( uri = "https://example.com/image.jpg", contentDescription = "photo", state = state, ) val result: ImageResult? = state.result val loadState: LoadState? = state.loadState val request: ImageRequest = loadState.request when (loadState) { is Started -> { } is Success -> { val memoryCacheKey: String = loadState.result.memoryCacheKey val resultCacheKey: String = loadState.result.resultCacheKey val downloadCacheKey: String = loadState.result.downloadCacheKey val imageInfo: ImageInfo = loadState.result.imageInfo val dataFrom: DataFrom = loadState.result.dataFrom val resize: Resize = loadState.result.resize val transformeds: List? = loadState.result.transformeds val extras: Map? = loadState.result.extras } is Error -> { val throwable: Throwable = loadState.result.throwable } is Canceled -> {} else -> { // null } } val progress: Progress? = state.progress val painterState: PainterState = state.painterState when (painterState) { is Loading -> {} is Success -> {} is Error -> {} } val painter: Painter? = state.painter // Reload state.restart() ``` -------------------------------- ### Get Image Loading Result Source: https://github.com/panpf/sketch/blob/main/docs/getting_started.md Retrieves the result of the last image loading operation for the ImageView. ```kotlin val imageResult: ImageResult? = imageView.imageResult ``` -------------------------------- ### Get Result Cache Key from ImageResult Source: https://github.com/panpf/sketch/blob/main/docs/result_cache.md Retrieve the result cache key from an ImageResult.Success object after a successful image execution. ```kotlin // Get the result cache key from ImageResult val imageSuccess = sketch.execute(request) as ImageResult.Success imageSuccess.resultCacheKey ``` -------------------------------- ### Custom Download Cache Key with ImageOptions Source: https://github.com/panpf/sketch/blob/main/docs/download_cache.md Shows how to set a custom download cache key using ImageOptions. ```kotlin ImageOptions { // Use custom download cache key downloadCacheKey("https://example.com/image.jpg?width=100&height=100") // Modify the automatically generated download cache key downloadCacheKeyMapper(CacheKeyMapper { "${it}&width=100&height=100" }) } ``` -------------------------------- ### Get Memory Cache Key from ImageResult Source: https://github.com/panpf/sketch/blob/main/docs/memory_cache.md Access the memory cache key associated with a successful image load from the ImageResult. ```kotlin // Get memory cache key from ImageResult val imageSuccess = sketch.execute(request) as ImageResult.Success imageSuccess.memoryCacheKey ``` -------------------------------- ### Load Images from iOS Photos Library Source: https://github.com/panpf/sketch/blob/main/docs/fetcher.md Demonstrates loading images from the iOS Photos Library using `newPhotosAssetUri()`. This method does not require additional modules. ```kotlin val imageUri = newPhotosAssetUri("DB16113B-984A-4D12-B4D0-50FC46066781/L0/001") // compose AsyncImage( uri = imageUri, contentDescription = "photo" ) // android viewimageView.loadImage(imageUri) ``` -------------------------------- ### Configure Resize, Size, Precision, and Scale Source: https://github.com/panpf/sketch/blob/main/docs/resize.md Set resize properties like width, height, precision, and scale simultaneously using the resize function. Alternatively, configure size, precision, and scale individually using their respective methods. ```kotlin ImageRequest(context, "https://example.com/image.jpg") { /* Set three properties at once */ resize( width = 100, height = 100, precision = Precision.SAME_ASPECT_RATIO, scale = Scale.END_CROP ) // or resize( size = Size(100, 100), precision = LongImagePrecisionDecider(Precision.SAME_ASPECT_RATIO), scale = LongImageScaleDecider(longImage = Scale.START_CROP, otherImage = Scale.CENTER_CROP) ) // or resize( size = FixedSizeResolver(100, 100), precision = LongImagePrecisionDecider(Precision.SAME_ASPECT_RATIO), scale = LongImageScaleDecider(longImage = Scale.START_CROP, otherImage = Scale.CENTER_CROP) ) /* Set size properties only */ size(100, 100) // or size(Size(100, 100)) // or size(FixedSizeResolver(100, 100)) /* Set precision properties only */ precision(Precision.SAME_ASPECT_RATIO) // or precision(LongImagePrecisionDecider(Precision.SAME_ASPECT_RATIO)) /* Set only scale properties */ scale(Scale.END_CROP) // or scale(LongImageScaleDecider(longImage = Scale.START_CROP, otherImage = Scale.CENTER_CROP)) } ``` -------------------------------- ### Configure Download Cache Options Source: https://github.com/panpf/sketch/blob/main/docs/download_cache.zh.md Customize the download cache implementation and its parameters during Sketch initialization. ```kotlin Sketch.Builder(context).apply { downloadCacheOptions( DiskCache.Options( // directory 和 appCacheDirectory 二选一即可 directory = "/tmp/myapp/sketch/download", // directory 和 appCacheDirectory 二选一即可 appCacheDirectory = "/tmp/myapp", // 100 MB maxSize = 1024 * 1024 * 100, // app 对下载缓存的管理版本号,如果想清除旧的下载缓存就升级此版本号 appVersion = 1, ) ) }.build() ``` -------------------------------- ### Use Custom DiskCache Implementation Source: https://github.com/panpf/sketch/blob/main/docs/download_cache.md Shows how to provide a custom DiskCache implementation to Sketch. ```kotlin // Use your own DiskCache implementation class MyDiskCache : DiskCache { // ... } Sketch.Builder(context).apply { downloadCache(MyDiskCache()) }.build() ``` -------------------------------- ### Customize Download Cache Options Source: https://github.com/panpf/sketch/blob/main/docs/download_cache.md Demonstrates how to customize the default LruDiskCache implementation and its parameters during Sketch initialization. ```kotlin Sketch.Builder(context).apply { downloadCacheOptions( DiskCache.Options( // Just choose one of directory and appCacheDirectory directory = "/tmp/myapp/sketch/download", // Just choose one of directory and appCacheDirectory appCacheDirectory = "/tmp/myapp", // 100 MB maxSize = 1024 * 1024 * 100, // The app's management version number for the download cache. // If you want to clear the old download cache, upgrade this version number. appVersion = 1, ) ) }.build() ``` -------------------------------- ### Adapt Component for Automatic Registration (JVM) Source: https://github.com/panpf/sketch/blob/main/docs/register_component.zh.md For JVM platforms, adapt your component by creating an actual implementation in jvmCommonMain, annotating it with @Keep, and defining its full name in 'resources/META-INF/services/com.github.panpf.sketch.util.ComponentProvider'. ```kotlin // jvmMain/resources/META-INF/services/com.github.panpf.sketch.util.ComponentProvider com.github.panpf.sketch.http.KtorHttpComponentProvider ``` -------------------------------- ### Get Download Cache Key from RequestContext Source: https://github.com/panpf/sketch/blob/main/docs/download_cache.md Explains how to access the download cache key from a RequestContext within custom components like Interceptors or Fetchers. ```kotlin // The download cache key can be obtained through RequestContext in the customized Interceptor, // Transformation, Fetcher, and Decoder components. val requestContext: RequestContext = ... requestContext.downloadCacheKey ``` -------------------------------- ### Add AppIcon Dependency Source: https://github.com/panpf/sketch/blob/main/docs/apk_app_icon.md Add the sketch-extensions-appicon dependency to your project to enable loading installed app icons. This module also supports automatic component registration. ```kotlin implementation("io.github.panpf.sketch4:sketch-extensions-appicon:${LAST_VERSION}") ``` -------------------------------- ### Customize Sketch with Singleton Factory (Non-Android) Source: https://github.com/panpf/sketch/blob/main/docs/getting_started.md Configure a custom Sketch instance using SingletonSketch.setSafe in non-Android environments. ```kotlin // Non Android. Called in the App entry function SingletonSketch.setSafe { Sketch.Builder(PlatformContext.INSTANCE).apply { logger(level = Logger.Level.Debug) // There is a lot more... }.build() } ``` -------------------------------- ### Load Images from Android Assets Source: https://github.com/panpf/sketch/blob/main/docs/fetcher.md Shows how to load images directly from the Android assets directory using the `newAssetUri()` function. No additional modules are needed. ```kotlin val imageUri = newAssetUri("image.jpg") val imageUri2 = newAssetUri("images/image.jpg") // compose AsyncImage( uri = imageUri, contentDescription = "photo" ) // android viewimageView.loadImage(imageUri) ``` -------------------------------- ### Get Memory Cache Key from RequestContext Source: https://github.com/panpf/sketch/blob/main/docs/memory_cache.md Retrieve the final memory cache key from a RequestContext, which is available in custom Interceptor, Transformation, Fetcher, and Decoder components. ```kotlin // The memory cache key can be obtained through RequestContext in the customized Interceptor, // Transformation, Fetcher, and Decoder components. val requestContext: RequestContext = ... requestContext.memoryCacheKey ``` -------------------------------- ### Display Image in ImageView with ImageViewTarget Source: https://github.com/panpf/sketch/blob/main/docs/target.md When displaying images in an Android ImageView, actively set the Target using ImageViewTarget. Ensure the ImageRequest is enqueued to start the loading process. ```kotlin ImageRequest(context, "https://www.example.com/image.jpg") { placeholder(R.drawable.placeholder) crossfade() target(imageView) }.enqueue(request) ``` -------------------------------- ### Adapt Component for Automatic Registration (Non-JVM) Source: https://github.com/panpf/sketch/blob/main/docs/register_component.zh.md For non-JVM platforms, use the @EagerInitialization annotation and ComponentLoader.register() in platform-specific directories (e.g., iosMain, wasmJsMain, jsMain) to ensure components are discovered. ```kotlin // iosMain or wasmJsMain @Suppress("DEPRECATION") @OptIn(ExperimentalStdlibApi::class) @EagerInitialization @Deprecated("", level = DeprecationLevel.HIDDEN) val ktorHttpComponentProviderInitHook: Any = ComponentLoader.register(KtorHttpComponentProvider()) ``` ```kotlin // jsMain @JsExport @Suppress("DEPRECATION") @OptIn(ExperimentalStdlibApi::class, ExperimentalJsExport::class) @EagerInitialization @Deprecated("", level = DeprecationLevel.HIDDEN) val ktorHttpComponentProviderInitHook: Any = ComponentLoader.register(KtorHttpComponentProvider()) ``` -------------------------------- ### Read, Write, and Remove from Result Cache Source: https://github.com/panpf/sketch/blob/main/docs/result_cache.md Access the result cache instance and use `withLock` for thread-safe operations. This snippet demonstrates getting, editing, and removing cache entries. ```kotlin scope.launch { val resultCache = sketch.resultCache val resultCacheKey = requestContext.resultCacheKey resultCache.withLock(resultCacheKey) { // get openSnapshot(resultCacheKey)?.use { snapshot -> val dataPath: Path = snapshot.data val metadataPath: Path = snapshot.metadata val dataContent = fileSystem.source(dataPath).buffer().use { it.readUtf8() } val metadataContent = fileSystem.source(metadataPath).buffer().use { it.readUtf8() } } // edit val editor: DiskCache.Editor? = openEditor(resultCacheKey) if (editor != null) { try { val dataPath: Path = editor.data val metadataPath: Path = editor.metadata fileSystem.sink(dataPath).buffer().use { it.writeUtf8("data") } fileSystem.sink(metadataPath).buffer().use { it.writeUtf8("metadata") } editor.commit() } catch (e: Exception) { editor.abort() } } // remove val cleared: Boolean = remove(resultCacheKey) } // Clear all resultCache.clear() } ``` -------------------------------- ### Load Image in Compose Multiplatform Source: https://github.com/panpf/sketch/blob/main/docs/getting_started.md Demonstrates various ways to load images using AsyncImage and Image with AsyncImagePainter in Compose Multiplatform. It shows how to specify image URIs and configure request options like placeholders and crossfade. ```kotlin val imageUri = "https://example.com/image.jpg" AsyncImage( uri = imageUri, contentDescription = "photo" ) ``` ```kotlin val imageUri = "https://example.com/image.jpg" AsyncImage( uri = imageUri, state = rememberAsyncImageState(ComposableImageOptions { placeholder(Res.drawable.placeholder) error(Res.drawable.error) crossfade() // There is a lot more... }), contentDescription = "photo" ) ``` ```kotlin val imageUri = "https://example.com/image.jpg" AsyncImage( rqeuest = ComposableImageRequest(imageUri) { placeholder(Res.drawable.placeholder) error(Res.drawable.error) crossfade() // There is a lot more... }, contentDescription = "photo" ) ``` ```kotlin val imageUri = "https://example.com/image.jpg" Image( painter = rememberAsyncImagePainter( request = ComposableImageRequest(imageUri) { placeholder(Res.drawable.placeholder) error(Res.drawable.error) crossfade() // There is a lot more... } ), contentDescription = "photo" ) ``` -------------------------------- ### Get Result Cache Key from RequestContext Source: https://github.com/panpf/sketch/blob/main/docs/result_cache.md Access the final result cache key within custom components like Interceptors, Transformations, Fetchers, and Decoders via the RequestContext. ```kotlin // The result cache key can be obtained through RequestContext in the customized Interceptor, // Transformation, Fetcher, and Decoder components. val requestContext: RequestContext = ... requestContext.resultCacheKey ``` -------------------------------- ### Custom Download Cache Key Source: https://github.com/panpf/sketch/blob/main/docs/download_cache.md Demonstrates how to set a custom download cache key for an ImageRequest. ```kotlin ImageRequest(context, "https://example.com/image.jpg") { // Use custom download cache key downloadCacheKey("https://example.com/image.jpg?width=100&height=100") // Modify the automatically generated download cache key downloadCacheKeyMapper(CacheKeyMapper { "${it}&width=100&height=100" }) } ``` -------------------------------- ### Load Thumbnail with URL Source: https://github.com/panpf/sketch/blob/main/docs/thumbnail.md Use the `thumbnail` function with a URL to load a lower-resolution version of the image first. This improves perceived loading speed. ```kotlin ImageRequest(context, "https://www.example.com/image.jpg") { thumbnail("https://www.example.com/image_thumbnail.jpg") } ``` -------------------------------- ### Desktop Download Cache Directory Source: https://github.com/panpf/sketch/blob/main/docs/download_cache.zh.md Specifies the default download cache directories for macOS, Windows, and Linux. ```kotlin val appName = (getComposeResourcesPath() ?: getJarPath(Sketch::class.java)).md5() // macOS "/Users/[user]/Library/Caches/SketchImageLoader/${appName}/sketch4/download" // Windows "C:\\Users\[user]\\AppData\\Local\\SketchImageLoader\\${appName}\\sketch4/download\\Cache" // Linux "/home/[user]/.cache/SketchImageLoader/${appName}/sketch4/download" ``` -------------------------------- ### Add Listener and ProgressListener to ImageRequest Source: https://github.com/panpf/sketch/blob/main/docs/listener.md Monitor image request lifecycle events (start, success, error, cancel) and progress using Listener and ProgressListener interfaces or lambda functions. All callbacks execute on the main thread. ```kotlin ImageRequest(context, "https://example.com/image.jpg") { addListener(object : Listener { override fun onStart(request: ImageRequest) { // ... } override fun onSuccess(request: ImageRequest, result: ImageResult.Success) { // ... } override fun onError(request: ImageRequest, error: ImageResult.Error) { // ... } override fun onCancel(request: ImageRequest) { // ... } }) // 或 addListener( onStart = { request: ImageRequest -> // ... }, onSuccess = { request: ImageRequest, result: ImageResult.Success -> // ... }, onError = { request: ImageRequest, error: ImageResult.Error -> // ... }, onCancel = { request: ImageRequest -> // ... }, ) addProgressListener { request: ImageRequest, progress: Progress -> // ... } } ``` -------------------------------- ### Load Images from Kotlin Resources Source: https://github.com/panpf/sketch/blob/main/docs/fetcher.md Illustrates loading images from Kotlin's resources directory, supporting iOS and Desktop platforms. Uses `newKotlinResourceUri()` and requires no additional modules. ```kotlin val imageUri = newKotlinResourceUri("images/sample.png") // compose AsyncImage( uri = imageUri, contentDescription = "photo" ) // android viewimageView.loadImage(imageUri) ``` -------------------------------- ### Use Custom DiskCache Implementation Source: https://github.com/panpf/sketch/blob/main/docs/download_cache.zh.md Replace the default DiskCache with a custom implementation. ```kotlin // 使用你自己的 DiskCache 实现 class MyDiskCache : DiskCache { // ... } Sketch.Builder(context).apply { downloadCache(MyDiskCache()) }.build() ``` -------------------------------- ### Initialize Ktor HTTP Component Provider (Non-JVM) Source: https://github.com/panpf/sketch/blob/main/docs/register_component.md For non-JVM platforms, initialize the Ktor HTTP Component Provider using ComponentLoader.register. Ensure the initialization hook name matches your ComponentProvider implementation. ```kotlin @Suppress("DEPRECATION") @OptIn(ExperimentalStdlibApi::class) @EagerInitialization @Deprecated("", level = DeprecationLevel.HIDDEN) val ktorHttpComponentProviderInitHook: Any = ComponentLoader.register(KtorHttpComponentProvider()) ``` -------------------------------- ### Load Images from Android ContentProvider Source: https://github.com/panpf/sketch/blob/main/docs/fetcher.md Illustrates loading images from an Android ContentProvider using its content URI. This method does not require additional modules. ```kotlin val imageUri = "content://media/external/file/13841" // compose AsyncImage( uri = imageUri, contentDescription = "photo" ) // android viewimageView.loadImage(imageUri) ``` -------------------------------- ### Initialize Ktor HTTP Component Provider (JS) Source: https://github.com/panpf/sketch/blob/main/docs/register_component.md For JavaScript platforms, initialize the Ktor HTTP Component Provider with @JsExport and @EagerInitialization. The initialization hook name must correspond to your ComponentProvider implementation. ```kotlin @JsExport @Suppress("DEPRECATION") @OptIn(ExperimentalStdlibApi::class, ExperimentalJsExport::class) @EagerInitialization @Deprecated("", level = DeprecationLevel.HIDDEN) val ktorHttpComponentProviderInitHook: Any = ComponentLoader.register(KtorHttpComponentProvider()) ``` -------------------------------- ### Load Images from Compose Multiplatform Resources Source: https://github.com/panpf/sketch/blob/main/docs/fetcher.md Shows how to load images from the `composeResources` directory in Compose Multiplatform projects. Requires the `sketch-compose-resources` module and uses `newComposeResourceUri()`. ```kotlin val imageUri = newComposeResourceUri("composeResources/com.github.panpf.sketch.sample.resources/files/sample.png") val imageUri2 = newComposeResourceUri(Res.getUri("files/sample.png")) // compose AsyncImage( uri = imageUri, contentDescription = "photo" ) ``` -------------------------------- ### Load Images from Android Resources Source: https://github.com/panpf/sketch/blob/main/docs/fetcher.md Demonstrates loading images from the Android `res` directory using `newResourceUri()`. This includes loading from the app's own resources and from other applications. ```kotlin val imageUri = newResourceUr(R.drawable.ic_launcher) val imageUri2 = newResourceUr("drawable", "ic_launcher") // Load images from other apps val imageUri = newResourceUr("com.android.launcher", R.drawable.ic_launcher) // Load images from other apps val imageUri2 = newResourceUr("com.android.launcher", "drawable", "ic_launcher") // compose AsyncImage( uri = imageUri, contentDescription = "photo" ) // android viewimageView.loadImage(imageUri) ``` -------------------------------- ### Preload Image Request Source: https://github.com/panpf/sketch/blob/main/docs/preload.md Create an ImageRequest with specific size, precision, and scale, then enqueue or execute it to preload the image. Ensure these parameters are consistent with how the image will be used later to guarantee cache hits. ```kotlin val request = ImageRequest(context, "https://example.com/image.jpg") { size(200, 200) precision(Precision.LESS_PIXELS) scale(Scale.CENTER_CROP) } sketch.enqueue(request) // or scope.launch { sketch.execute(request) } ``` -------------------------------- ### Configure KtorStack for Sketch Source: https://github.com/panpf/sketch/blob/main/docs/http.md Configure KtorStack by providing a pre-configured HttpClient. Disable the default KtorHttpComponentProvider before adding custom components. ```kotlin Sketch.Builder(context).apply { addIgnoredComponentProvider(KtorHttpComponentProvider::class) addComponents { val httpClient = HttpClient { // ... } val httpStack = KtorStack(httpClient) addFetcher(KtorHttpUriFetcher.Factory(httpStack)) } }.build() ``` -------------------------------- ### Configure Resize, Size, Precision, and Scale Source: https://github.com/panpf/sketch/blob/main/docs/resize.zh.md Configure resizing properties for an ImageRequest. You can set all three attributes (size, precision, scale) at once, or set them individually. Use Size, PrecisionDecider, and ScaleDecider for more advanced configurations. ```kotlin ImageRequest(context, "https://example.com/image.jpg") { /* 一次设置三个属性 */ resize( width = 100, height = 100, precision = Precision.SAME_ASPECT_RATIO, scale = Scale.END_CROP ) // 或 resize( size = Size(100, 100), precision = LongImagePrecisionDecider(Precision.SAME_ASPECT_RATIO), scale = LongImageScaleDecider(longImage = Scale.START_CROP, otherImage = Scale.CENTER_CROP) ) // 或 resize( size = FixedSizeResolver(100, 100), precision = LongImagePrecisionDecider(Precision.SAME_ASPECT_RATIO), scale = LongImageScaleDecider(longImage = Scale.START_CROP, otherImage = Scale.CENTER_CROP) ) /* 仅设置大小属性 */ size(100, 100) // 或 size(Size(100, 100)) // 或 size(FixedSizeResolver(100, 100)) /* 仅设置精度属性 */ precision(Precision.SAME_ASPECT_RATIO) // 或 precision(LongImagePrecisionDecider(Precision.SAME_ASPECT_RATIO)) /* 仅设置缩放属性 */ scale(Scale.END_CROP) // 或 scale(LongImageScaleDecider(longImage = Scale.START_CROP, otherImage = Scale.CENTER_CROP)) } ``` -------------------------------- ### Android View: loadImage with Options Source: https://github.com/panpf/sketch/blob/main/README.md Configure image loading with placeholders, error images, and crossfade animations using the loadImage extension function with a lambda for options. ```kotlin val imageUri = "https://www.sample.com/image.jpg" imageView.loadImage(imageUri) { placeholder(R.drawable.placeholder) error(R.drawable.error) crossfade() // There is a lot more... } ``` -------------------------------- ### Configure OkHttpStack for Sketch Source: https://github.com/panpf/sketch/blob/main/docs/http.md Manually configure OkHttpStack with custom timeouts, user agent, headers, and both network and regular interceptors. Disable the default OkHttpHttpComponentProvider before adding custom components. ```kotlin Sketch.Builder(context).apply { addIgnoredComponentProvider(OkHttpHttpComponentProvider::class) addComponents { val httpStack = OkHttpStack.Builder().apply { connectTimeout(5000) readTimeout(5000) userAgent("Android 8.1") headers("accept-encoding" to "gzip") // non-repeatable header addHeaders("cookie" to "...") // repeatable header interceptors(object : okhttp3.Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() // ... return chain.proceed(request) } }) networkInterceptors(object : okhttp3.Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() // ... return chain.proceed(request) } }) }.build() addFetcher(OkHttpHttpUriFetcher.Factory(httpStack)) } }.build() ``` -------------------------------- ### Download Image with enqueueDownload and executeDownload Source: https://github.com/panpf/sketch/blob/main/docs/download_image.md Use enqueueDownload() for asynchronous downloads or executeDownload() for synchronous downloads. Both methods return a Result containing DownloadData on success or an exception on failure. DownloadData can be of type Cache (providing a path) or Bytes (providing raw byte data). ```kotlin val imageUri = "https://example.com/image.jpg" val deferred: Deferred> = sketch .enqueueDownload(ImageRequest(context, imageUri)) scope.launch { val result = deferred.await() val data: DownloadData = result.getOrNull() if (data != null) { // success if (data is DownloadData.Cache) { val path: Path = data.path } else if (data is DownloadData.Bytes) { val bytes: ByteArray = data.bytes } } else { // failed val throwable = result.exceptionOrNull() } } // or scope.launch { val result = sketch.executeDownload(ImageRequest(context, imageUri)) val data: DownloadData = result.getOrNull() if (data != null) { // success if (data is DownloadData.Cache) { val path: Path = data.path } else if (data is DownloadData.Bytes) { val bytes: ByteArray = data.bytes } } else { // failed val throwable = result.exceptionOrNull() } } ``` -------------------------------- ### Read, Edit, and Remove Cache Entries Source: https://github.com/panpf/sketch/blob/main/docs/download_cache.zh.md Demonstrates how to safely access, modify, and delete cache entries using downloadCache.withLock. ```kotlin scope.launch { val downloadCache = sketch.downloadCache val downloadCacheKey = imageRequest.downoadCacheKey downloadCache.withLock(downloadCacheKey) { // get openSnapshot(downloadCacheKey)?.use { snapshot -> val dataPath: Path = snapshot.data val metadataPath: Path = snapshot.metadata val dataContent = fileSystem.source(dataPath).buffer().use { it.readUtf8() } val metadataContent = fileSystem.source(metadataPath).buffer().use { it.readUtf8() } } // edit val editor: DiskCache.Editor? = openEditor(downloadCacheKey) if (editor != null) { try { val dataPath: Path = editor.data val metadataPath: Path = editor.metadata fileSystem.sink(dataPath).buffer().use { it.writeUtf8("data") } fileSystem.sink(metadataPath).buffer().use { it.writeUtf8("metadata") } editor.commit() } catch (e: Exception) { editor.abort() } } // remove val cleared: Boolean = remove(downloadCacheKey) } // Clear all downloadCache.clear() } ``` -------------------------------- ### Configure Download Cache Policy Source: https://github.com/panpf/sketch/blob/main/docs/download_cache.md Illustrates how to set the download cache policy for an ImageRequest, including disabling, read-only, and write-only modes. ```kotlin ImageRequest(context, "https://example.com/image.jpg") { // Disable downloadCachePolicy(CachePolicy.DISABLED) // Read only downloadCachePolicy(CachePolicy.READ_ONLY) // Write Only downloadCachePolicy(CachePolicy.WRITE_ONLY) } ``` -------------------------------- ### Configure Default Memory Cache Source: https://github.com/panpf/sketch/blob/main/docs/memory_cache.md Configure the default memory cache implementation with custom parameters like maximum size percentage. ```kotlin Sketch.Builder(context).apply { memoryCache( MemoryCache.Builder(context) .maxSizePercent(0.4f) .build() ) }.build() ``` -------------------------------- ### Load Image with AsyncImage Source: https://github.com/panpf/sketch/blob/main/docs/compose.md Use AsyncImage to directly load and display images. It handles asynchronous requests and rendering. You can provide a URI, or configure placeholder, error images, and crossfade effects using a state object or a ComposableImageRequest. ```kotlin val imageUri = "https://example.com/image.jpg" AsyncImage( uri = imageUri, contentDescription = "photo" ) ``` ```kotlin AsyncImage( uri = imageUri, state = rememberAsyncImageState(ComposableImageOptions { placeholder(Res.drawable.placeholder) error(Res.drawable.error) crossfade() // There is a lot more... }), contentDescription = "photo" ) ``` ```kotlin AsyncImage( rqeuest = ComposableImageRequest(imageUri) { placeholder(Res.drawable.placeholder) error(Res.drawable.error) crossfade() // There is a lot more... }, contentDescription = "photo" ) ``` -------------------------------- ### Load Image from Base64 String Source: https://github.com/panpf/sketch/blob/main/docs/fetcher.md Use newBase64Uri() to create a URI from a Base64 string for loading images. This method does not require additional modules. ```kotlin val base64String = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxISEhUTE" val imageUri = "data:image/jpeg;base64,${base64String}" val imageUri = newBase64Uri("image/jpeg", base64String) // compose AsyncImage( uri = imageUri, contentDescription = "photo" ) // android view imageView.loadImage(imageUri) ``` -------------------------------- ### Display Image in Compose with AsyncImage Source: https://github.com/panpf/sketch/blob/main/docs/target.md Use AsyncImage for displaying images in Compose. The target is automatically set, so focus on other request parameters like placeholders and crossfade. ```kotlin AsyncIage( rqeuest = ComposableImageRequest("https://example.com/image.jpg") { placeholder(Res.drawable.placeholder) crossfade() }, contentDescription = "photo", ) ``` -------------------------------- ### Desktop Result Cache Directories Source: https://github.com/panpf/sketch/blob/main/docs/result_cache.md Provides default result cache directory paths for macOS, Windows, and Linux. The appName is derived from the application's path or JAR file. ```kotlin val appName = (getComposeResourcesPath() ?: getJarPath(Sketch::class.java)).md5() // macOS "/Users/[user]/Library/Caches/SketchImageLoader/${appName}/sketch4/result" // Windows "C:\\Users\[user]\\AppData\\Local\\SketchImageLoader\\${appName}\\sketch4/result\\Cache" // Linux "/home/[user]/.cache/SketchImageLoader/${appName}/sketch4/result" ``` -------------------------------- ### Use BlurHash as a Placeholder Source: https://github.com/panpf/sketch/blob/main/docs/blurhash.md Configure an ImageRequest to use BlurHash as a placeholder. Ensure the size aspect ratio matches the original image to avoid deformation. Be mindful of UI thread performance when decoding. ```kotlin ImageRequest(context, "https://www.example.com/image.svg") { placeholder( BlurHashStateImage( blurHash = "d7D+0q5W00^h01~A~B0gInR%?G9vR%R+NH=_I;NG$$-o", size = Size(200, 300) ) ) // or blurHashPlaceholder( blurHash = "d7D+0q5W00^h01~A~B0gInR%?G9vR%R+NH=_I;NG$$-o", size = Size(200, 300) ) // You can also pass the size through uri blurHashPlaceholder( blurHash = newBlurHashUri( blurHash = "d7D+0q5W00^h01~A~B0gInR%?G9vR%R+NH=_I;NG$$-o", size = Size(200, 300) ) ) // You can also limit the size by using the maxSide property, BlurHashStateImage will scale blur images in a ratio blurHashPlaceholder( blurHash = "d7D+0q5W00^h01~A~B0gInR%?G9vR%R+NH=_I;NG$$-o", size = Size(200, 300), maxSide = 100 ) // BlurHashStateImage will use memory cache to accelerate decoding. You can control the cachePolicy attribute. BlurHashStateImage to use memory cache. blurHashPlaceholder( blurHash = "d7D+0q5W00^h01~A~B0gInR%?G9vR%R+NH=_I;NG$$-o", size = Size(200, 300), maxSide = 100, cachePolicy = CachePolicy.DISABLED ) // Fallback and error can also be used with BlurHashStateImage } ``` -------------------------------- ### Use Singleton Mode for Sketch Source: https://github.com/panpf/sketch/blob/main/docs/getting_started.md Access a shared Sketch instance directly using context or SingletonSketch.get() for simplified image loading. ```kotlin // Android val sketch = context.sketch val sketch = SingletonSketch.get(context) // Non Android val sketch = SingletonSketch.get() // Compose AsyncImage( uri = "https://www.example.com/image.jpg", moidifier = Modifier.fillMaxSize(), contentDescription = "photo", ) // View imageView.loadImage(uri = "https://www.example.com/image.jpg") // or ImageRequest(imageView, uri = "https://www.example.com/image.jpg").enqueue(request) ``` -------------------------------- ### Compose Multiplatform: AsyncImage with State Source: https://github.com/panpf/sketch/blob/main/README.md Configure AsyncImage with custom states, including placeholders, error images, and crossfade animations using rememberAsyncImageState. Ensure the 'sketch-compose-resources' module is imported for drawable resources. ```kotlin val imageUri = "https://www.sample.com/image.jpg" AsyncImage( uri = imageUri, state = rememberAsyncImageState(ComposableImageOptions { placeholder(Res.drawable.placeholder) error(Res.drawable.error) crossfade() // There is a lot more... }), contentDescription = "photo" ) ``` -------------------------------- ### Load Image with Extensions Source: https://github.com/panpf/sketch/blob/main/docs/getting_started.md Loads an image into an ImageView with options for placeholder, error drawable, and crossfade animation. This function is only available in singleton mode. ```kotlin imageView.loadImage("https://www.example.com/image.jpg") { placeholder(R.drawable.placeholder) error(R.drawable.error) crossfade(true) } ``` -------------------------------- ### Customize Sketch with Singleton Factory (Android) Source: https://github.com/panpf/sketch/blob/main/docs/getting_started.md Implement the SingletonSketch.Factory interface in your Application class to create a customized Sketch instance. ```kotlin // Android class MyApplication : Application(), SingletonSketch.Factory { override fun createSketch(): Sketch { return Sketch.Builder(context).apply { logger(level = Logger.Level.Debug) // There is a lot more... }.build() } } ``` -------------------------------- ### ImageRequest with Merged and Default Options Source: https://github.com/panpf/sketch/blob/main/docs/image_options.md Construct an ImageRequest and merge custom ImageOptions, also providing default ImageOptions. The merge options take higher priority. ```kotlin ImageRequest(context, "https://example.com/image.jpg") { merge(ImageOptions { placeholer(R.drawable.placeholder) error(R.drawable.error) // more ... }) default(ImageOptions { placeholer(R.drawable.placeholder) error(R.drawable.error) // more ... }) } ``` -------------------------------- ### iOS Download Cache Directory Source: https://github.com/panpf/sketch/blob/main/docs/download_cache.md Defines the default download cache directory path on iOS. ```kotlin val appCacheDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, true).first() as String val downloadCacheDir = "$appCacheDirectory/sketch4/download" ```