1public void imageEncoderDecoder() throws IOException {
2
3 // image path declaration
4 String imgPath = "src/main/resources/images/bean.png";
5
6 // read image from file
7 FileInputStream stream = new FileInputStream(imgPath);
8
9 // get byte array from image stream
10 int bufLength = 2048;
11 byte[] buffer = new byte[2048];
12 byte[] data;
13
14 ByteArrayOutputStream out = new ByteArrayOutputStream();
15 int readLength;
16 while ((readLength = stream.read(buffer, 0, bufLength)) != -1) {
17 out.write(buffer, 0, readLength);
18 }
19
20 data = out.toByteArray();
21 String imageString = Base64.getEncoder().withoutPadding().encodeToString(data);
22 byte[] decodeImg = Base64.getDecoder().decode(imageString);
23 out.close();
24 stream.close();
25
26 // System.out.println("Encode Image Result : " + imageString);
27 System.out.println("Decode Image Result : " + Arrays.toString(decodeImg));
28}
1 public static void main(String[] args) throws Exception{
2
3 File f = new File("/opt/myImage.jpg");
4 String encodstring = encodeFileToBase64Binary(f);
5 System.out.println(encodstring);
6 }
7
8 private static String encodeFileToBase64Binary(File file) throws Exception{
9 FileInputStream fileInputStreamReader = new FileInputStream(file);
10 byte[] bytes = new byte[(int)file.length()];
11 fileInputStreamReader.read(bytes);
12 return new String(Base64.encodeBase64(bytes), "UTF-8");
13 }
14