-
-
Save LluisFelip/f36e09ea0b0c4a4c4e6b0c5d255627ac to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun getClient(): WebViewClient { | |
return object : WebViewClient() { | |
override fun shouldInterceptRequest( | |
view: WebView?, | |
request: WebResourceRequest? | |
): WebResourceResponse? { | |
return super.shouldInterceptRequest(view, request) | |
} | |
override fun shouldInterceptRequest(view: WebView?, url: String?): WebResourceResponse? { | |
if (url == null) { | |
return super.shouldInterceptRequest(view, url as String) | |
} | |
val interceptedUrl = url.toLowerCase(Locale.ROOT) | |
val cachableImage = CachableImage.getMatchingImage(interceptedUrl) | |
return when { | |
cachableImage != null -> { | |
val bitmap = Glide.with(webView) | |
.asBitmap() | |
.diskCacheStrategy(DiskCacheStrategy.ALL) | |
.load(interceptedUrl) | |
.submit() | |
.get() | |
WebResourceResponse( | |
cachableImage.mimeType, | |
"UTF-8", | |
getBitmapInputStream( | |
bitmap, | |
cachableImage.compressFormat, | |
) | |
) | |
} | |
else -> super.shouldInterceptRequest(view, interceptedUrl) | |
} | |
} | |
} | |
} | |
enum class CachableImage( | |
val suffixes: Set<String>, | |
val mimeType: String, | |
val compressFormat: Bitmap.CompressFormat, | |
) { | |
JPG(setOf("jpg", "jpeg"), "image/jpg", Bitmap.CompressFormat.JPEG), | |
PNG(setOf("png"), "image/png", Bitmap.CompressFormat.PNG), | |
WEBP(setOf("webp"), "image/webp", Bitmap.CompressFormat.WEBP_LOSSY); | |
companion object { | |
fun getMatchingImage(url: String): CachableImage? = values().find { image -> | |
image.suffixes.any { url.contains(".$it") } | |
} | |
} | |
} | |
private fun getBitmapInputStream(bitmap: Bitmap, compressFormat: Bitmap.CompressFormat): InputStream = | |
ByteArrayInputStream( | |
ByteArrayOutputStream().apply { | |
bitmap.compress(compressFormat, 80, this) | |
}.toByteArray() | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment