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 = != -1) {

     imageRaw = out.toByteArray();

  } catch (IOException e) {
     // TODO Auto-generated catch block

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

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

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

Leave a Comment