importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.Base64;publicclassImageToBase64Converter{publicstaticvoidmain(String[]args){try{StringimagePath="path/to/your/image.jpg";Stringbase64String=convertImageToBase64(imagePath);System.out.println("Base64 String: "+base64String);}catch(IOExceptione){e.printStackTrace();}}privatestaticStringconvertImageToBase64(StringimagePath)throwsIOException{FileimageFile=newFile(imagePath);if(imageFile.exists()){FileInputStreamfileInputStream=newFileInputStream(imageFile);byte[]imageData=newbyte[(int)imageFile.length()];fileInputStream.read(imageData);fileInputStream.close();returnBase64.getEncoder().encodeToString(imageData);}else{thrownewIOException("Image file not found: "+imagePath);}}}
Replace "path/to/your/image.jpg" with the actual path to your image file. This code reads the image file, converts it to a byte array, and then encodes the byte array into a Base64 string.
Sharing is caring!