Monday, April 15, 2024

Android add custom bitmap to Fresco image library cache

fun addCache(key: String, bitmap: Bitmap) {
    // add cache to memory
    val cacheKey = SimpleCacheKey(key)
    val imagePipeline = Fresco.getImagePipeline()
    val closeableBitmap = CloseableStaticBitmap(
        bitmap,
        {
            it.recycle()
        },
        ImmutableQualityInfo.FULL_QUALITY,
        0, 0
    )

    imagePipeline.bitmapMemoryCache.cache(cacheKey, CloseableReference.of(closeableBitmap))

    // add cache to disk
    val stream = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
    val byteArray = stream.toByteArray()
    Fresco.getImagePipelineFactory().mainFileCache.insert(cacheKey) { outputStream ->
        outputStream.write(byteArray)
    }
}