Java 将解码的base64字节数组写入图像文件

Java 将解码的base64字节数组写入图像文件,java,Java,问题是数据被完全传输了,如果数据是文本格式,它会正确显示。然而,当我试图解码图像并将其写入输出文件时,它不会简单地显示在照片查看器中 一旦我必须将图像转换为base 64并以流的形式发送该图像(这里是编码和解码的代码),我将非常感谢任何帮助 要将文件转换为base64,请执行以下操作: String base64Code = dataInputStream.readUTF(); byte[] decodedString = null; decodedString =

问题是数据被完全传输了,如果数据是文本格式,它会正确显示。然而,当我试图解码图像并将其写入输出文件时,它不会简单地显示在照片查看器中


一旦我必须将图像转换为base 64并以流的形式发送该图像(这里是编码和解码的代码),我将非常感谢任何帮助

要将文件转换为base64,请执行以下操作:

    String base64Code = dataInputStream.readUTF();

    byte[] decodedString = null;

    decodedString = Base64.decodeBase64(base64Code);


    FileOutputStream imageOutFile = new FileOutputStream(
    "E:/water-drop-after-convert.jpg");
    imageOutFile.write(decodedString);

    imageOutFile.close(); 
然后在服务端,我做了类似的事情,将Base64字符串中的图像转换回文件,以便显示。 我在服务器端使用了这个库
import sun.misc.BASE64Decoder

String filePath = "E:\\water-drop-after-convert.jpg";
File bMap =  new File(filePath);
byte[] bFile = new byte[(int) bMap.length()];
        FileInputStream fileInputStream = null;
        String imageFileBase64 = null;

        try {
            fileInputStream = new FileInputStream(bMap);
            fileInputStream.read(bFile);
            fileInputStream.close();
            imageFileBase64 = Base64.encode(bFile);   
        }catch(Exception e){
            e.printStackTrace();
        }

DataInputStream.readUTF可能是问题所在。此方法假定文本是由DataOutputStream.writeUTF写入文件的。如果不是这样,并且您要阅读常规文本,请选择其他类,如BufferedReader或Scanner。或者Java 1.7的文件。readAllBytes。

与其向我们展示有效的代码,为什么不展示无效的代码(图像转换代码)?那么也许我们可以帮助。@T.J.Crowder图像编写代码写在上面。。。它将图像写入e驱动器中的jpg,但当我尝试打开图像时,图像查看器中没有显示图像,但是文件大小等于传输的原始文件。好的,从你的问题听起来,你好像在做其他事情。上面的代码看起来很适合转换Base-64字符串并将其写入文件。所以你必须走过去看看哪里出了问题。最明显的问题是您收到的Base-64字符串有问题。Base-64字符串非常好,因为当发送简单文本时,它会解码并显示文本,但它无法将解码的字节作为图像文件写入驱动器EWajih,请查看代码。可能的问题很少。要么字符串错误(仅仅因为其中包含文本,这并不意味着文本是正确的),要么
Base64.decodeBase64
函数错误,要么
FileOutputStream#write
错误。您必须在调试器中浏览代码并查看它是哪一个(我可以告诉您,它不太可能是最后一个)。请不要在不检查返回的读取字节数的情况下读取输入流。这只是一个示例。。。提示…,程序员将自行实现各种验证
//filePath is where you wana save image
                String filePath = "E:\\water-drop-after-convert.jpg";
                File imageFile = new File(filePath);
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(imageFile);
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            }
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] decodedBytes = null;
            try {
                decodedBytes = decoder.decodeBuffer(imageFileBase64);//taking input string i.e the image contents in base 64
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                fos.write(decodedBytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }