如何在Java中将Image转换为base64字符串?


问题内容

可能是重复的,但我面临将图像转换成Base64用于发送的问题Http Post。我已经尝试过此代码,但是它给了我错误的编码字符串。

 public static void main(String[] args) {

           File f =  new File("C:/Users/SETU BASAK/Desktop/a.jpg");
             String encodstring = encodeFileToBase64Binary(f);
             System.out.println(encodstring);
       }

       private static String encodeFileToBase64Binary(File file){
            String encodedfile = null;
            try {
                FileInputStream fileInputStreamReader = new FileInputStream(file);
                byte[] bytes = new byte[(int)file.length()];
                fileInputStreamReader.read(bytes);
                encodedfile = Base64.encodeBase64(bytes).toString();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return encodedfile;
        }

输出: [B @ 677327b6

但我将同一张图像转换Base64为许多在线编码器,它们都给出了正确的大Base64字符串。

编辑: 如何重复?我的重复的链接没有给我解决方案转换字符串我想要的。

我在这里想念什么?


问题答案:

问题是您要返回toString()的调用将Base64.encodeBase64(bytes)返回一个字节数组。因此,最后得到的是字节数组的默认字符串表示形式,它与您获得的输出相对应。

相反,您应该执行以下操作:

encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");