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:

<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 nhận xét:

Đăng nhận xét