它可能是重复的,但我在将图像转换为 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 字符串。
编辑: 它是如何重复的?与我重复的链接并没有给我转换我想要的字符串的解决方案。
我在这里想念什么?
原文由 Setu Kumar Basak 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题是您正在返回
toString()
调用Base64.encodeBase64(bytes)
返回一个字节数组。所以你最终得到的是一个字节数组的默认字符串表示,它对应于你得到的输出。相反,您应该这样做: