Android - Local Image in Webview

How to load local images with webview on Android 11.0?

The cause of the problem was eventually discovered.
This is because the webSetting.setAllowFileAccess method defaults to true in 29 and earlier versions, and false in 30 and later versions.

 /**
* Enables or disables file access within WebView.
* Note that this enables or disables file system access only. Assets and resources
* are still accessible using file:///android_asset and file:///android_res.
* <p class="note">
* <b>Note:</b> Apps should not open {@code file://} URLs from any external source in
* WebView, don't enable this if your app accepts arbitrary URLs from external sources.
* It's recommended to always use
* <a href="{@docRoot}reference/androidx/webkit/WebViewAssetLoader">
* androidx.webkit.WebViewAssetLoader</a> to access files including assets and resources over
* {@code http(s)://} schemes, instead of {@code file://} URLs. To prevent possible security
* issues targeting {@link android.os.Build.VERSION_CODES#Q} and earlier, you should explicitly
* set this value to {@code false}.
* <p>
* The default value is {@code true} for apps targeting
* {@link android.os.Build.VERSION_CODES#Q} and below, and {@code false} when targeting
* {@link android.os.Build.VERSION_CODES#R} and above.
*/
public abstract void setAllowFileAccess(boolean allow);

So add follow code solve this problem:

binding.webView.getSettings().setAllowFileAccess(true);

of cause let targetSdkVersion <=29 will also okey.

How to load local image in Android WebView

Try like this

String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
String imagePath = "file://"+ base + "/image_name.jpg";
String html = "<html><head></head><body> <img src=\""+ imagePath + "\"> </body></html>";
webView.loadDataWithBaseURL("", html, "text/html","utf-8", "");

Loading an image from local android storage to WebView

So I found a solution to what I wanted to do and I'm posting an answer here if anyone someday wonders into this post and wants to know the solution.

Basically after taking a picture I call the javascript function which puts the taken image inside my .html file between <img></img> tags as the source.
This is my onActivityResult in MainActivity.java:

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
//Getting the full image path of the image taken
final String imagePath = "file://"+ currentPhotoPath;
webView.post(new Runnable() {
@Override
public void run() {
webView.evaluateJavascript("postImage('" + imagePath + "')", null);
}
});
getLocation();
if (data == null) {
//Display an error
Log.d("performClick", "Error: data == null");
return;
}
}
}

What it does is it calls the javascript function postImage and passes imagePath as a parameter and the function in my hello.js file is:

function postImage(imagePath){
document.body.innerHTML = "<img src=\""+ imagePath + "\">";
}

Now once I take the picture it appears on my WebView as an image without needing to reload the page or loading another URL with only the image.

Android - local image in webview

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");  

WebView on Android 11 - not showing local image files

Try setting webview.getSettings().setAllowFileAccess(true);. The documentation says:

The default value is true for apps targeting Build.VERSION_CODES.Q and
below, and false when targeting Build.VERSION_CODES.R and above.

Rendering a local HTML file with a local image in WebView

Following CommonWare's suggestion, I will answer this question and state what worked for me. I was also able to scale the image independently of the text.

I was unable to get the image to render when my image and html file were in the res/raw directory. I tried many combinations and failed. I will not state that it is impossible.

What DID work was creating a directory named assets at the same level as the src directory and placing BOTH my image file and html file in that directory. As CommonWare pointed out, the URL for the files is

"file:///android_asset/main_screen_crop.png"

even though the directory name is 'assets'.

The code simplifies to

    LayoutInflater inflater = ((Activity)context).getLayoutInflater();
@SuppressLint("InflateParams") // Okay on dialog
final View helpContent = inflater.inflate(R.layout.help_screen, null);

// Get the Alert Dialog Builder
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context);

TextView customTitle = new TextView(context);
// Customise Title here
customTitle.setText(title);
customTitle.setBackgroundColor(context.getResources().getColor(R.color.colorToolbarBackground));
customTitle.setPadding(10, 10, 10, 10);
customTitle.setGravity(Gravity.CENTER);
customTitle.setTextColor(Color.WHITE);
customTitle.setTextSize(20);

builder.setCustomTitle(customTitle);

WebView help = helpContent.findViewById(R.id.helpView);
help.setWebViewClient(new WebViewClient()
{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});

help.getSettings().setAllowFileAccess(true);
help.loadUrl(htmlpage);

builder.setView(helpContent);

where 'htmlpage' is, for example,

"file:///android_asset/layout_help.html"

The html file itself (with independent scaling of text and image) becomes:

<html>
<head>
<style>
.gfg {
width:auto;
text-align:center;
padding:2px;
}
img {
max-width:100%;
height:auto;
}
</style>
</head>
<body>
<h3>Running the Application</h3>
After pressing start you will see a screen as follows:
<div class="gfg">
<p id="my-image">
<img src="file:///android_asset/main_screen_crop.png" alt="Main Screen"/>
</p>
</div>
</html>

Hope this saves someone the 7 hrs it took me to get it to work.

Android - Show Local Images in WebView

Try creating a web pages in your assets directory and creating HTML pages that display the images. Then call a web page using this:

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

Or, according to one of the posts in your link, move the html file to a server and use this code:

loadDataWithBaseUrl("content://<your contentProvider>/blacksmoke.html", ...);

Code in blacksmoke.html could be:

<!DOCTYPE html>
<!-- Perhaps some JQuery mobile for more functionality and control over which images get displayed and why etc -->
<body>
<div><img src="image/blacksmoke1.jpg"></div>
</body>
</html>

Here is a good explanation for creating native pages or displaying native images.

Android WebView - Open Local Images


How do I do this for local images?

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

Here is my main.html:

<html>
<head>

</head>
<body>
<h1>Login Form</h1>
<img src="download.jpg" width="200px" onClick="Foo.SomeMethod('bla-bla')"></img>
</body>
</html>

Then, load that Html file in Webview:

webView.LoadUrl("file:///android_asset/main.html");

how do I handle click on images in HTML inside the WebView

You could refer to:

  • Monodroid Javascript Call-back
  • Call C# from JavaScript

Here is a simple demo:

public class MainActivity: Activity
{
class Foo : Java.Lang.Object // do not need Java.Lang.IRunnable
{
Context context;

public Foo(Context context)
{
this.context = context;
}

[Export] // !!! do not work without Export
[JavascriptInterface] // This is also needed in API 17+
public void SomeMethod(string param)
{
Toast.MakeText(context, "This is a Toast from C#!" + param, ToastLength.Short).Show();
}
}

protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);

SetContentView(Resource.Layout.Main);

WebView view = FindViewById<WebView>(Resource.Id.web);
view.Settings.JavaScriptEnabled = true;
view.AddJavascriptInterface(new Foo(this), "Foo");
view.LoadUrl("file:///android_asset/main.html");
}
}

Load Image from local private directory in a webview

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);


Related Topics



Leave a reply



Submit