Answers for "base64 to image java"

1

java image to base64 example

public void imageEncoderDecoder() throws IOException {

    // image path declaration
    String imgPath = "src/main/resources/images/bean.png";

    // read image from file
    FileInputStream stream = new FileInputStream(imgPath);

    // get byte array from image stream
    int bufLength = 2048;
    byte[] buffer = new byte[2048];
    byte[] data;

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int readLength;
    while ((readLength = stream.read(buffer, 0, bufLength)) != -1) {
        out.write(buffer, 0, readLength);
    }

    data = out.toByteArray();
    String imageString = Base64.getEncoder().withoutPadding().encodeToString(data);
   byte[] decodeImg = Base64.getDecoder().decode(imageString);
    out.close();
    stream.close();

    // System.out.println("Encode Image Result : " + imageString);
    System.out.println("Decode Image Result : " + Arrays.toString(decodeImg));
}
Posted by: Guest on September-10-2021
0

java:image to base64 string example

       public static void main(String[] args) throws Exception{
 
           File f =  new File("/opt/myImage.jpg");
             String encodstring = encodeFileToBase64Binary(f);
             System.out.println(encodstring);
       }
 
       private static String encodeFileToBase64Binary(File file) throws Exception{
            FileInputStream fileInputStreamReader = new FileInputStream(file);
            byte[] bytes = new byte[(int)file.length()];
            fileInputStreamReader.read(bytes);
            return new String(Base64.encodeBase64(bytes), "UTF-8");
        }
Posted by: Guest on June-10-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language