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

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;

}

Output: [B@677327b6

But i converted this same image into Base64 in many online encoders and they all gave the correct big Base64 string.

Edit: How is it a duplicate?? The link which is duplicate of mine doesn't give me solution of converting the string what i wanted.

What am i missing here??

解决方案

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.

Instead, you should do:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值