53

What I have: I'm loading image from a URL. I simply do (WebView).loadUrl(imageurl, extraheaders)

What I get: Image is not showing at full width of the WebView, it has blank space all around (like if you open a little iamge in your desktop browser)

What i tried: Setting LayoutAlgorithm to SINGLE_COLUMN. Works perfect, but zooming doesn't work. (I have it enabled in the WebView.getSettings() Dont know why. Setting setUseWideViewPort(true); load image without any blanks space, but it is fully zoomed in.

Sarim Sidd
  • 2,166
  • 2
  • 22
  • 31
artouiros
  • 3,947
  • 12
  • 41
  • 54

11 Answers11

99

You could also do something like this.

Add CSS style for img at the beginning (depends on your web data format) of your data string.

<style>img{display: inline; height: auto; max-width: 100%;}</style>

To quickly do it to data in WebView i did this.

WebView content = (WebView) findViewById(R.id.webView1);
content.loadDataWithBaseURL(null, "<style>img{display: inline;height: auto;max-width: 100%;}</style>" + post.getContent(), "text/html", "UTF-8", null);

It's pretty much like what bansal21ankit said, but instead it will work on every image in your HTML without extra work.


Edit (clarification on post content):

You can have any text/html value instead of post.getContent() from the example.

Post content here is just an example of a text/html content which is loaded from some data source and then concatenated with the style part which makes any image in given content to fit the screen.

Tony
  • 1,433
  • 1
  • 15
  • 18
  • @Tony...can you explain the post_content part of your post? How do I get that with an URL? Thanks! – Johnny Wu Apr 18 '16 at 03:06
  • @JohnnyWu updated the answer with info on `post.getContent()` part. – Tony Apr 19 '16 at 17:40
  • Hi, this really helps. But how about video? Sorry, I'm not a web developer so I don't know about CSS. – Dark Leonhart Mar 19 '18 at 09:32
  • That depends on the way you embed your video, that can be done via `iframe` tag, `video` tag or possibly in some other way, so it might be difficult to find a unified solution that would look good, but to quickly reuse the solution in the answer you could try ``. Link to full example: https://jsfiddle.net/ssrq2d6t/17/ – Tony Mar 19 '18 at 19:08
  • 1
    I have an Image with data, then it is not working :( – Amin Pinjari May 08 '19 at 08:14
  • It just worked perfectly ❤️ – mustafiz012 Feb 27 '23 at 22:09
60

I had the same issue and doing this worked just fine:

Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();

String data = "<html><head><title>Example</title><meta name=\"viewport\"\"content=\"width="+width+", initial-scale=0.65 \" /></head>";
data = data + "<body><center><img width=\""+width+"\" src=\""+url+"\" /></center></body></html>";
webView.loadData(data, "text/html", null);

Edit: As this remained as the accepted answer, here is a better solution (all credit to Tony below):

WebView content = (WebView) findViewById(R.id.webView1);
content.loadDataWithBaseURL(null, "<style>img{display: inline;height: auto;max-width: 100%;}</style>" + post.getContent(), "text/html", "UTF-8", null);
fawaad
  • 341
  • 6
  • 12
Sebastian Breit
  • 6,137
  • 1
  • 35
  • 53
  • 1
    Thanks, is it any way to send extra headers(e.g referer), while using this structure? – artouiros May 03 '12 at 05:45
  • 2
    see Tony answer below, that is the one that works across platforms and devices – 2cupsOfTech Jun 10 '14 at 19:56
  • in my case, when loading html data with image, without forcing style like above resulting infinite scroll (webview trying to adjust the height without edge) thus crash occurred in android 9 & above. the `loadDataWithBaseUrl` + ` – mochadwi Jun 14 '20 at 13:16
44

you should scale the webView to fit the screen:

 WebView data = (WebView) getViewById(R.id.webview1);
 data.getSettings().setLoadWithOverviewMode(true);
 data.getSettings().setUseWideViewPort(true);
thepoosh
  • 12,497
  • 15
  • 73
  • 132
  • 9
    If the image size is bigger then a screen it will not make image fit the screen but screen fit the image (it will look like someone zoomed out to see the whole content) – supermus Mar 27 '13 at 15:59
  • 2
    @supermus When LoadWithOverviewMode and UseWideViewPort are both enabled the image *will* fit the screen. I develop for API level 16 and your statement isn't true regarding this version. I upvote this answer. – 3k- Aug 12 '13 at 15:57
  • Don't exactly the same issue but this worked for me, I used the image in an html file that I load to the webview. webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setUseWideViewPort(true); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setSaveFormData(true); webView.getSettings().setBuiltInZoomControls(true); webView.loadUrl("file:///android_asset/your_file.html"); – magorich Feb 09 '15 at 18:35
10

Its a bit late but I hope this will help, what you can do is:

String html = "<html><body><img src=\"" + URL + "\" width=\"100%\" height=\"100%\"\"/></body></html>";
mWebView.loadData(html, "text/html", null);

this will make the image exactly similar to your WebView's width, rest you can adjust the WebView itself.

Ankit Bansal
  • 1,801
  • 17
  • 34
  • 1
    This maybe a little late, but zoom cotrols doesn't work using this approach. But it's cool and charming :) – Farhad May 16 '14 at 06:02
9

What worked for me was this: I read that in order to fit the width of the screen you should add this to your HTML or xml inside the field:

width="100%"

So what I did was, instead of scaling and zooming the images, I got the xml, put it in a StringBuilder, found the src="https://blablabla.com/image.png" that is inside the field and just before the "src" substring I inserted the "width="100%"", then y set my webView with the StringBuilder, mi code is this:

public void setWebViewWithImageFit(String content){

        // content is the content of the HTML or XML.
        String stringToAdd = "width=\"100%\" ";

        // Create a StringBuilder to insert string in the middle of content.
        StringBuilder sb = new StringBuilder(content);

        int i = 0;
        int cont = 0;

        // Check for the "src" substring, if it exists, take the index where 
        // it appears and insert the stringToAdd there, then increment a counter
        // because the string gets altered and you should sum the length of the inserted substring
        while(i != -1){
            i = content.indexOf("src", i + 1);
            if(i != -1) sb.insert(i + (cont * stringToAdd.length()), stringToAdd );
            ++cont;
        }

        // Set the webView with the StringBuilder: sb.toString()
        WebView detailWebView = (WebView) findViewById(R.id.web_view);
        detailWebView.loadDataWithBaseURL(null, sb.toString(), "text/html", "utf-8", null);
}

Hope this helps, it took me some hours to figure out how to solve this.

9

Code:

web = (WebView) findViewById(R.id.at_image_web);
web.getSettings().setBuiltInZoomControls(true);
web.getSettings().setUseWideViewPort(true);
web.getSettings().setJavaScriptEnabled(true);
web.getSettings().setLoadWithOverviewMode(true);
web.loadUrl(linkImage);
Mike
  • 4,550
  • 4
  • 33
  • 47
1

This work for me: webView = (WebView) findViewById(R.id.webView); WebSettings webSettings = webView.getSettings(); webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);

Jenkyn
  • 199
  • 2
  • 10
0

I think this will fix your issue:-

      WebView web;

      web = (WebView) findViewById(R.id.webkit);
      web.setWebViewClient(new Callback());
      web.getSettings().setJavaScriptEnabled(true);
      web.getSettings().setLoadWithOverviewMode(true);
      web.getSettings().setUseWideViewPort(true);
      web.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
      web.setScrollbarFadingEnabled(false);
Nibha Jain
  • 7,742
  • 11
  • 47
  • 71
user755278
  • 1,634
  • 3
  • 16
  • 32
  • 2
    It's not the scrollbar issue, my blank space is like 50% of the screen. Still the same. It's like the image is zoomed out more, than the screen size. – artouiros May 01 '12 at 08:36
0

This Code Work For Me :

String strData = "<head>" + "<style>" + ".smal-video-pnl,.smal-video-thumb,.detail-hldr{margin-left: 0px;margin-right:0px;}" + "</style>" +
            "</head>" + mListItem.get(position).getTitbits();
holder.webViewStatus.loadDataWithBaseURL(null, strData, "text/html", "UTF-8", null);
0
@BindingAdapter("wvSetContent")
fun WebView.wvSetContent(content: String?) {
    this.isFocusable = true
    this.isFocusableInTouchMode = true
    this.settings.javaScriptEnabled = true
    this.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
    this.settings.setRenderPriority(WebSettings.RenderPriority.HIGH)
    this.settings.cacheMode = WebSettings.LOAD_DEFAULT
    this.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

    this.settings.domStorageEnabled = true
    this.settings.loadsImagesAutomatically = true;
    this.settings.setAppCacheEnabled(true)
    this.settings.databaseEnabled = true
    this.settings.setSupportMultipleWindows(false)
    this.loadDataWithBaseURL(null,
        "<style>img{display: inline;height: auto;max-width: 100%;}</style>$content", "text/html", "UTF-8", null)
}

it worked for me

Sang Nguyen
  • 23
  • 1
  • 4
0

I have noticed if we are using this CSS image gets fit in the screen width but the height remains same which looks image is compressed from the side.

<style>img{display: inline; height: auto; max-width: 100%;}</style>

So to avoid that I just did one simple change in this code only. Just put the width: 100%; first and then put height: auto; It did work for me perfectly.

<style>img{display: inline; max-width: 100%; height: auto;}</style>

By the way thanks Tony for the beautiful solution.