Android - local image in webview

I'm trying to diplay a local image in my webview :

 String data = "<body>" + "<img src=\"file:///android_asset/large_image.png\"/></body>";
 webview.loadData(data, "text/html", "UTF-8");

This code doesn't display anything, instead of :

 webview.loadUrl("file:///android_asset/large_image.jpg");

This one works, but I need to have complex web page, not just a picture.

Any ideas ?


Load Html file in Webview and put your image in asset folder and read that image file using Html.

<html>
  <table>
    <tr>
      <td>
        <img src="abc.gif" width="50px" alt="Hello">
      </td>
    </tr>
  </table>
</html>

Now Load that Html file in Webview

webview.loadUrl("file:///android_asset/abc.html");  

You can also try

String data = "<body>" + "<img src=\"large_image.png\"/></body>";

webView.loadDataWithBaseURL("file:///android_asset/",data , "text/html", "utf-8",null);

One convenient way (often forgotten) is to use base64 embedded images in HTML content. This will also work on mobile Webkit browsers (IOS, Android..).

Point of using this method is that you can embed images on HTML content, instead of fighting with image links from webview to restricted filesystem.

  <img src="data:image/jpg;base64,xxxxxxxxxxxxxxxxxxxxxxxxxxxx"/>

  xxxxx = base64 encoded string of images bytes

If you want to provide (base64 embedded) image data from filesystem, you can for example:

1) In Android use ContentProvider - which will provide base64 formatted image strings.

<img src="content://.............."/>

2) Or you can preprocess HTML with JSOUP or similar DOM parser (before setting it to webview) and adjust image src with properly base64 encoded image.

Disadvantages of this method is overhead included in converting image to base64 string and of course in proding larger HTML data to webview.