将解码后的base64字节数组写为图像文件

时间:2012-12-09 07:39:52

标签: java

    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(); 

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

任何帮助都将受到高度赞赏

2 个答案:

答案 0 :(得分:0)

一旦我不得不将Image转换为base 64并将该图像作为流发送(这里的编码和解码内容就是代码)

将文件转换为base64:

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();
        }

然后在服务端我做了类似的事情将base 64 String中的图像转换回文件,这样我就可以显示了。 我在服务器端import sun.misc.BASE64Decoder;

使用了这个库
//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();
            }

答案 1 :(得分:0)

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

相关问题