0

I am note sure what is wrong with the below code. I am trying to encode an JPG file with base64 encoding. After encoding i am checking is it base64 encoded, it returns false. I am unable to find what is that I am missing.

    public String  encodeBinary64(String value){
     String output = null;
     System.out.println("encoding the binary length "+value.length());

    byte[] byteArray = Base64.encodeBase64(value.getBytes());
         output = Arrays.toString(byteArray);

          System.out.println("output length encoding"+output.length());
          Boolean base64Encoded = Base64.isBase64(output); -- returning FALSE

          System.out.println("Base 64 Encoded "+ base64Encoded );


     return output;

 }

Update 2

The solution suggested below helped. However after decoding the base64 encoded image, when i try to open I am getting windows Photo Viewer Can't Open message. Below is the code.

         public String  decodeBinary64(String value){
     String output = null;
     System.out.println("Decoding the binary length "+value.length());

      Boolean base64Encoded = Base64.isBase64(value);
       System.out.println("base64Encoded "+base64Encoded);
      if(base64Encoded){
          byte[] byteArray = Base64.decodeBase64(value.getBytes());
        try {
            output =   new String(byteArray, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

          System.out.println("output length "+output.length());
      }


     return output;

 }

Note:

I have verified the length of the file before encoding and after decoding. The size remains the same. But the file is unable to open.

1 Answer 1

1

Arrays.toString(), on the array of bytes [1, 2, 3], returns the string "[1, 2, 3]".

What you want is new String(byteArray, "ASCII").

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.