28

I'd like something:

s="
<body>

<img src='"+R.drawable.picture+"'>

</body>";

How can I do this?

lacas
  • 13,928
  • 30
  • 109
  • 183
  • Check out the accepted answer to [this question](http://stackoverflow.com/questions/1792604/html-imagegetter), regarding Html.ImageGetter. They do exactly what you want. – Ridcully Mar 21 '12 at 09:55
  • Possible duplicate of [@Android display /res/viewable in WebView](http://stackoverflow.com/questions/2630829/android-display-res-viewable-in-webview) – rds Jun 23 '16 at 14:38

4 Answers4

52

You can only do such a thing if our image is inside your /assets folder. Also, you must load your html with a baseUrl that's inside your assets folder.

You can use WebView.loadUrl() or WebView.loadDataWithBaseURL():

webView.loadUrl("file:///android_asset/file.html");

or

webView.loadDataWithBaseURL("file:///android_asset/", "<img src='file.jpg' />", "text/html", "utf-8", null);

(file.jpg should be inside your assets folder)

Jonas Alves
  • 1,306
  • 12
  • 17
  • 18
    `webView.loadDataWithBaseURL` can load images from drawables. just replace `"file:///android_asset/"` with `"file:///android_res/drawable/"` – dumbfingers Oct 11 '12 at 13:29
  • @JonasAlves: Do you know how to do the webview.loadUrl trick with an Android Resource Drawable? Something like ``? I don't know which is the path to the system resource drawables. – Luis A. Florit Dec 22 '13 at 21:08
  • Even though I read this a few times I wrongly assumed the "most load your html with a baseUrl that's inside your assets folder" part was only needed if you wanted to use a relative path for the src attribute. Turns out, for whatever weird reasons (security?), this is actually required. Using full URLs for the src is not enough. – eselk Jun 17 '15 at 17:46
  • This is the only working variant with TAPI 26 for me. Thanks! – halxinate Dec 15 '18 at 20:45
51

After some experimenting I found that the following HTML worked on Android 2.3.1 (but not on older versions):

<img src="file:///android_res/drawable/example.png"/>

The really cool part is that the image file was actually in the directory drawable-hdpi but the resource manager provides the image in the standard directory drawable.

Lal
  • 14,726
  • 4
  • 45
  • 70
Eric Obermühlner
  • 1,076
  • 9
  • 9
6

Try this:

 web_object.loadDataWithBaseURL("file:///android_res/drawable/", "<img src='test.jpg' />", "text/html", "utf-8", null);

no need to make seprate html file

Pranav
  • 4,172
  • 3
  • 30
  • 31
1

Set Image Width 100%.

wv.loadDataWithBaseURL("file:///android_res/drawable/", "<img src='"+ url + "' style='width:100%' />", "text/html", "utf-8", null); 
    wv.getSettings().setBuiltInZoomControls(true);
    wv.getSettings().setDisplayZoomControls(false);