如何在java中将图像转换为base64字符串? [英] How to convert an Image to base64 string in java?

查看:26
本文介绍了如何在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字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆