如何在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字符串。

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

我在这里失踪了什么?

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

相反,你应该这样做:

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

我想你可能想要:

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

这样做对我来说。 您可以将输出格式的选项更改为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);