How to display image with WebView loaddata?

It is possible to embedd the base64 encoded imagedata direct into the <img>-tag:

  <img src="data:image/jpeg;base64,base64DataHere" />

Here an example for creating the <img>-tag (I use an byte-array instead the String for raw-data, because in my tests an String as source didn’t work – I assume that String can’t handle binary-data):

  byte[] imageRaw = yourImage;
  String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT);
  String pageData = "<img src=\"data:image/jpeg;base64," + image64 + "\" />";

The Base64-class was introduced with API v.2.2 – for older API-versions you can copy the sourcefile from git and integrate it in your app. It should work with older API-versions.

Or you can use one of the alternative classes for base64-encoding like Base64Coder.


And here the complete working code for retrieving, converting and showing the image:

  byte[] imageRaw = null;
  try {
     URL url = new URL("http://some.domain.tld/somePicture.jpg");
     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     ByteArrayOutputStream out = new ByteArrayOutputStream();

     int c;
     while ((c = in.read()) != -1) {
         out.write(c);
     }
     out.flush();

     imageRaw = out.toByteArray();

     urlConnection.disconnect();
     in.close();
     out.close();
  } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
  }

  String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT);

  String urlStr   = "http://example.com/my.jpg";
  String mimeType = "text/html";
  String encoding = null;
  String pageData = "<img src=\"data:image/jpeg;base64," + image64 + "\" />";

  WebView wv;
  wv = (WebView) findViewById(R.id.webview);
  wv.loadDataWithBaseURL(urlStr, pageData, mimeType, encoding, urlStr);

Leave a Comment