Resizing images in an Android WebView

Posted: October 12th, 2010 | Author: | Filed under: Android | Tags: ,

In one of my current projects I have to show HTML “the app” pulls from an RSS feed. Unfortunately, the editors of that site felt it necessary to hard wire height and width attributes into each image; a little hack was necessary to override the widths … “no horizontal scrolling” is pretty much the rule, right? So, thanks to an old tip from lexandera, I was off.

Alexander’s suggestions still hold true — Thank Crunchy. In my case, I have the HTML in a local store and simply need to push it into a WebView.

It goes something like this:

final WebView web = (WebView) findViewById( R.id.webView );
web.loadDataWithBaseURL( null,
  content,
  "text/html",
  "UTF-8",
  null);

That loadDataWithBaseUrl call was needed to force local characters. Not sure if that’s the best option but it works and dammit if I’m changing it. The result for HTML that was so lucky to include <img width=”bajilion” /> is, well, crap.

Now, to implement the resizing bits. First, old school javascript:

final String js = "javascript:(function () {
  var w = " + width + ";
  for( var i = 0; i < document.images.length; i++ ) {
    var img = document.images[i];
    if( img.width > w ) {
      img.height = Math.round( img.height * ( w/img.width ) );
      img.width = w;
      img.style.display='block';
    };
  }
})();";

That “width” variable is the width of the default display minus a bit of padding. You’ll also note that all images have been hidden. To do that, I just added <style>img{display:none}</style> to the HTML that was fed to web.loadDataWithBaseURL. The last step in the JS chain is to make them visible. I’m not a javascript genius; that’s obvious.

Now, the funk. It’s basically  – no, it’s exactly — Alexander’s approach:

web.setWebViewClient( new WebViewClient(){
  @Override
  public void onPageFinished(WebView view, String url) {
    web.loadUrl( js );
  }
});

Some points:

  1. setting max-width and width via css didn’t work. Seems the WebView doesn’t automatically proportion sizes.
  2. For pages with many images, this is not an ideal solution. Images suddenly “pop” up; users hate that I’m sure.

I’m eyes wide open for alternatives.

Edit: I decided to take a different route altogether in order to keep the performance a bit under control. A bit of hacking with HtmlCleaner to remove any height and width attributes plus a simple img { max-width: XXX; } injected into the HTML <head> did the trick.  It’s still a hack but a hack that works.

facebook comments:


Leave a Reply