Friday 9 July 2010

In line images

Many web sites include small images and icons in tool bars and menus. These images are downloaded one by one by the browser while the page is downloaded. In many cases, the establishing of connection is more expensive in terms of time and traffic than the actual image. By converting these images to base64 encoding text, the browser can download the page content and the images at one go. Here’s is the code of how to convert an image into a base64 string.

public static String convertToInLineImage(
    byte[] image, String type) {
// Convert a byte array to base64 string
char[] chars = new sun.misc.BASE64Encoder().
                    encode(image).toCharArray();
StringBuilder builder = new StringBuilder();
for (char c : chars) {
 switch (c) {
   case '\n':
   case '\r':
   continue;
 default:
   builder.append(c);
 }
}

return "data:" + type + ";base64," + builder.toString();
}

The above method simple converts an image from bytes into string. The string returned by this method should be placed within the image HTML style.

style="width:50px;
      height:50px;
      background:url('the-base64-string-here')
          no-repeat scroll 0px 0px transparent;"