How to convert an Image to base64 string in java?(如何在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");
这篇关于如何在java中将图像转换为base64字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在java中将图像转换为base64字符串?
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
