How to encode an image and display as html in angular


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

<dependency>
 <groupId>commons-codec</groupId>
 <artifactId>commons-codec</artifactId>
 <version>1.11</version>
</dependency>

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.

<img src="#{imagePath}" />

0 Comments

Post a Comment

Post a Comment (0)

Previous Post Next Post
NERV Open Source
Building production Spring Boot systems?

Explore NERV — open-source Java libraries for audit trails, persistence, exception handling, and reliable event-driven architecture.