如何在 java 中将图像转换为 base64 字符串?

How to convert an Image to base64 string in java?

它可能是重复的,但我在将图像转换为 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 字符串。

编辑:怎么重复了??与我重复的 link 没有给我转换字符串的解决方案。

我在这里错过了什么??

这是为我做的。您可以将输出格式的选项更改为 Base64.Default 。

// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);

我想你可能想要:

String encodedFile = Base64.getEncoder().encodeToString(bytes);

问题是您要返回 Base64.encodeBase64(bytes) 调用的 toString(),其中 returns 是一个字节数组。所以你最后得到的是一个字节数组的默认字符串表示,对应你得到的输出。

相反,您应该这样做:

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