Convert WebView To Image in Android — Step by Step Guide

Maithili Joshi
2 min readSep 30, 2020

--

Converting a webview to Image typically works like taking a screenshot of the webview.

A problem I faced while doing this was when webview height overshot the screen height. In that case, only a part of the webview was being stored as an Image.

After research, I found out a way to dynamically calculate webview width and height after it has been rendered. The following blog shows a step by step guide to do this.

  1. If the webview height overshoots the screen height, then we dynamically calculate the webview height. To do this, there is a prerequisite. Add the following property before the webview loads (preferably in the onCreateView of the fragment)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
WebView.enableSlowWholeDocumentDraw()
}

2. Convert webview to Bitmap : In this we measure the webview and draw on Canvas with the measured width and height. Refer the code below..

// measure the webview
webView.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED)
)
//layout of webview
webView.layout(0, 0, webView.measuredWidth, webView.getMeasuredHeight())

webView.isDrawingCacheEnabled = true
webView.buildDrawingCache()
//create Bitmap if measured height and width >0
val b = if (webView.measuredWidth> 0 && webView.measuredHeight> 0)Bitmap.createBitmap(
webView.measuredWidth,
webView.measuredHeight, Bitmap.Config.ARGB_8888
)
else null
// Draw bitmap on canvas
b?.let {
Canvas(b).apply {
drawBitmap(it, 0f, b.height.toFloat(), Paint())
webView.draw(this)
}
}

Here b will contain the Bitmap of our webview.

3. Save the Bitmap as image in the desired location. This works the same way as saving any other file in Android. Given the directory, filename, the following code will create a file and save in the given location.

fun saveBitmapToFile(directory: File, fileName: String, b: Bitmap) {
if (!directory.exists()) {
directory.mkdirs()
}
val file = File(directory, fileName)

try {
val out = FileOutputStream(file)
b.compress(Bitmap.CompressFormat.JPEG, 100, out)
out.flush()
out.close()
} catch (e: Exception) {
e.printStackTrace()
}
}

In the above code, the Bitmap is saved as .JPEG file. You can choose any other image format that you want like .PNG.

Want to read this story later? Save it in Journal.

Note : — Step #3 requires additional Android permissions namely WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE. Do not forget to ask for user permission.

And that’s it. Your webview is successfully stored in the location of your choice. Hope this helps fellow developers stuck with the same issue and makes their lives easier.

Do let me know if you have any problems, I will be glad to help.

More from Journal

There are many Black creators doing incredible work in Tech. This collection of resources shines a light on some of us:

--

--