簡體   English   中英

將解碼的base64字節數組寫入圖像文件

[英]Writing decoded base64 byte array as image file

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

問題是數據已完全傳輸,並且如果數據為文本格式,則可以正確顯示,但是當我嘗試解碼圖像並將其寫入輸出文件時,它並不會簡單地顯示在照片查看器中。

任何幫助將不勝感激

一旦我不得不將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;使用了該庫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();
            }

DataInputStream.readUTF可能是問題。 此方法假定文本是由DataOutputStream.writeUTF寫入文件的。 如果不是這樣,並且您要閱讀常規文本,請選擇其他類,例如BufferedReader或Scanner。 或Java 1.7的Files.readAllBytes。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM