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

Set*_*sak 20 java base64 image

它可能是重复但我面临一些问题,将图像转换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;
        }
Run Code Online (Sandbox Code Playgroud)

输出: [B @ 677327b6

但我将这个相同的图像转换成Base64许多在线编码器,它们都给出了正确的大Base64字符串.

编辑:怎么重复?我的副本链接并没有给我转换字符串我想要的解决方案.

我在这里失踪了什么?

Lol*_*olo 26

问题是你toString()Base64.encodeBase64(bytes)返回一个返回字节数组的调用.所以你最终得到的是字节数组的默认字符串表示形式,它对应于你得到的输出.

相反,你应该这样做:

encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");
Run Code Online (Sandbox Code Playgroud)

  • String strBase64 = Base64.encodeToString(byteArray,0) (4认同)

Joe*_*Elf 9

我想你可能想要:

String encodedFile = Base64.getEncoder().encodeToString(bytes);
Run Code Online (Sandbox Code Playgroud)


Moj*_*oMS 7

这是为我做的。您可以将输出格式的选项更改为 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);
Run Code Online (Sandbox Code Playgroud)