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.
Use this method.
mview.loadDataWithBaseURL(folder.getAbsolutePath(), content, "text/html", "windows-1252", "");
folder.getAbsolutePath()
can be "file:///android_asset"
or just "/"
I think there is a \
missing in your code
String data = "<body>" + "<img src=\\"file:///android_asset/large_image.png\"/></body>";
The image will not load unless you have:
webSettings.setAllowFileAccessFromFileURLs(true);
If you are using a html file, it should be in a folder called "assets" in /app/src/main. If you don't have that folder then make it. Then load the html file with:
myWebView.loadUrl("file:///android_asset/test.html");
If you put the image in the same folder as the html file, then in the html file you can just do a normal:
<img src='myimage.jpg' />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With