如何在java中将图像转换为base64字符串?
它可能是重复的,但我在将图像转换为 Base64
以将其发送到 Http Post
时遇到一些问题.我试过这段代码,但它给了我错误的编码字符串.
It may be a duplicate but i am facing some problem to convert the image into Base64
for sending it for Http Post
. I have tried this code but it gave me wrong encoded string.
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 字符串.
Output: [B@677327b6
But i converted this same image into Base64
in many online encoders and they all gave the correct big Base64 string.
它是如何重复的?与我的链接重复的链接并没有给我转换我想要的字符串的解决方案.
How is it a duplicate?? The link which is duplicate of mine doesn't give me solution of converting the string what i wanted.
我错过了什么?
推荐答案
问题是你正在返回调用 Base64.encodeBase64(bytes)
的 toString()
code> 返回一个字节数组.所以你最后得到的是一个字节数组的默认字符串表示,它对应你得到的输出.
The problem is that you are returning the toString()
of the call to Base64.encodeBase64(bytes)
which returns a byte array. So what you get in the end is the default string representation of a byte array, which corresponds to the output you get.
相反,您应该这样做:
encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");
相关文章