Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Image from local private directory in a webview

Context :

My app sometimes displays "Sheets" which are html files that contain texts and images :

<p>image description </p>
<p><img src="/api/medias/get/videos/56afad6447eba61c8099544b?thumbnail=true&amp;company=4f86d0a9d655ab9794f5d1d2&amp;fullSizedCover=true" 
    alt="" 
    data-id="56afad6447eba61c8099544b" 
    data-type="video" data-width="640" data-height="1136" /></p>

Then I use body.loadDataWithBaseURL(<my api url>, body, "text/html; charset=UTF-8", null, null);

I don't think it's relevant but I'll say it just in case, I have a template body that contains css and javascript. the js script detect images click and transmit the "data-id" to an android method (via a JavascriptInterface). In this case it opens a video player and plays it.


Problem :

My app allow the user to download these Sheets for latter offline vizualisation. So I download the html, then download the images to my local private directory (Context.getFileDir()) and change the src of the html to set the "thumbnail" sources to the images I downloaded :

<p>video</p>
<p><img src="69c623955ecb5bd414f908cd383f3809.jpg" 
    alt="" 
    data-id="56afad6447eba61c8099544b" 
    data-type="video" data-width="640" data-height="360" /></p>

My question is : What do I put as base url to my webview for me to get the expected behaviour (ie : display the downloaded images).

I tried Context.getFileDir().getAbsolutePath(), content://com.android.htmlfileprovider and some other.

Should I do differently ?

Thank a lot,


This works well:

Picasso.with(iv.getContext()).load(new File(getContext().getFilesDir() + "/" + "69c623955ecb5bd414f908cd383f3809.jpg")).into(iv);

The html :

<p>video</p>
<p><img src="69c623955ecb5bd414f908cd383f3809.jpg" alt="" data-id="56afad6447eba61c8099544b" data-type="video" data-width="640" data-height="360" /></p>

my base url : baseUrl = Uri.fromFile(getContext().getFilesDir()).toString();

And finaly : webview.loadDataWithBaseURL(baseUrl, body, "text/html; charset=UTF-8", null, null);

like image 288
Renaud Favier Avatar asked Nov 29 '16 15:11

Renaud Favier


1 Answers

You can try to use null baseUrl if you already downloaded/have template, and just pass that html template as a body to webview. And before passing find img tags in it and set img src with a full path to locally stored file. Smth like:

Document doc = Jsoup.parse(newHtml);
Elements elems = doc.getElementsByTag("img");
for (Element el : elems) {
    String filename = el.attr("src"); //presumably only name
    String picUri = "file:///" + folder + "/"+filename;
    el.attr("src", picUri);   
}
web.loadDataWithBaseURL(null, htmlBody, "text/html", "UTF-8", null);
like image 183
shtolik Avatar answered Oct 15 '22 00:10

shtolik