Encode image and display in html

Encode image and display in html

Encode image and display in html

To encode an image file(eg. png, jpg, gif) we will need the apache commons-codec library.
To avoid it in a maven project:


 commons-codec
 commons-codec
 1.11

Encode a file:

public static String encodeFileToBase64Binary(File file) throws IOException {
 String encodedFile = null;
 try (FileInputStream fileInputStreamReader = new FileInputStream(file)) {
  byte[] bytes = new byte[(int) file.length()];
  fileInputStreamReader.read(bytes);
  encodedFile = org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);
 }

 return encodedFile;
}

Prepare the image:

String strImage = encodeFileToBase64Binary(new File(imagePath));
String imageExt = FilenameUtils.getExtension(imagePath);

imagePath = "data:image/" + imageExt + ";charset=utf-8;base64, " + strImage;

Now you can use imagePath in your HTML.


Leave a Reply