2012-04-19 178 views
23

我在將gif圖像轉換爲基本64字符串時遇到問題。Java - 將圖像轉換爲Base64

當我轉換它時,代碼爲我增加了10萬個AAAAAA,而圖像真的很小!

這裏是我的代碼:

import java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileWriter; 
import java.util.ArrayList; 

public class Main 
{ 

    public static void main(String[] args) 
    { 
     try 
     { 
      FileWriter fstream = new FileWriter("./out.txt"); 
      BufferedWriter out = new BufferedWriter(fstream); 

      File folder = new File("./flags/"); 
      File[] listOfFiles = folder.listFiles(); 

      for (int i = 0; i < listOfFiles.length; i++) 
      { 
       if (listOfFiles[i].isFile()) 
       { 
        Main.readFile(out, listOfFiles[i]); 
       } 
      } 

      out.close(); 
      System.out.println("Done"); 
     } 
     catch (Exception e) {} 
    } 

    public static void readFile(BufferedWriter out, File file) 
    { 
     try 
     { 
      byte[] byteArray = new byte[102400]; 
      FileInputStream fis = new FileInputStream(file); 
      String base64String; 
      int bytesRead = 0; 
      while ((bytesRead = fis.read(byteArray)) != -1) 
      { 
       new String(byteArray, 0, bytesRead); 
       base64String = Base64.encode(byteArray); 
       out.write("public static ImageIcon getFlag" + file.getName() + "()"); 
       out.newLine(); 
       out.write("{"); 
       out.newLine(); 
       ArrayList<String> array = Main.cut(base64String); 
       out.write("return Utils.toImage(\"" + array.get(0) + "\""); 
       for (int i=1; i<array.size()-1; i++) 
       { 
        out.write("<tab>+\"" + array.get(i) + "\""); 
       } 
       out.write("<tab>\"" + array.get(array.size() - 1) + "\");"); 
       out.newLine(); 
       out.write("}"); 
       out.newLine(); 
       out.newLine(); 
      } 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 

    public static ArrayList<String> cut(String in) 
    { 
     ArrayList<String> array = new ArrayList<String>(); 
     while (in.length() > 76) 
     { 
      array.add(in.substring(0, 77)); 
      in = in.substring(77); 
     } 
     return array; 
    } 
} 

Basicaly,它在一個文本文件out.txt一堆Java方法裏面基64碼寫入。

這裏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ge的代碼 – UVM 2012-04-19 10:22:39

+0

你是否將圖像作爲整個字節數組傳遞給Base64編碼器? – 2012-04-19 10:23:02

回答

49
byte[] byteArray = new byte[102400]; 
base64String = Base64.encode(byteArray); 

無論數據中實際使用多少數據,該代碼都會對102400個字節進行編碼。

while ((bytesRead = fis.read(byteArray)) != -1) 

你需要使用bytesRead的地方值。另外,這可能不會一次將整個文件讀入數組中(它只讀取I/O緩衝區中的數據),因此您的循環可能不起作用,最終可能會有一半圖像在你的數組中。

我在這裏使用Apache的百科全書IOUtils:

Base64.encode(FileUtils.readFileToByteArray(file)); 
+1

你說byte [] byteArray = new byte [102400]只在這個字節數內編碼,這是否意味着它只讀取那個大小的字節,其餘的不會被讀取? – 2012-10-04 06:36:47

+0

它讀取和編碼該數組中包含的所有102400個字節。 – Thilo 2012-10-04 10:09:57

+0

我在哪裏可以得到這個Apache通用IOUtils jar文件?我有commons-io-1.4.jar。當我導入到eclipse並使用你的代碼:'Base64.encode(FileUtils.readFileToByteArray(f));'沒有這樣的方法,並且我得到以下_方法編碼(byte [],int)Base64類型不適用於參數(byte [])_ – 2013-08-27 05:15:26

5

首先,這行代碼:

while ((bytesRead = fis.read(byteArray)) != -1) 

相當於

while ((bytesRead = fis.read(byteArray, 0, byteArray.length)) != -1) 

所以這寫入從offset 0開始的byteArray,而不是從之前寫入的地方開始。

你需要的東西是這樣的:

int offset = 0; 
int bytesRead = 0; 

while ((bytesRead = fis.read(byteArray, offset, byteArray.length - offset) != -1) { 
    offset += bytesRead; 
} 

您在隨後讀取數據(字節)後,就可以將其轉換爲Base64。

雖然存在更大的問題 - 您使用的是固定大小的數組,因此太大的文件將無法正確轉換,並且代碼也因此而更加狡猾。

我會溝字節數組,像這樣的東西去:

ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 
// commons-io IOUtils 
IOUtils.copy(fis, buffer); 
byte [] data = buffer.toByteArray(); 
Base64.encode(data); 

或進一步壓縮它作爲蒂洛與文件實用程序。

+0

我不明白這一點,'fis'是一個'FileInputStream',所以如果你從它讀取,那麼你讀的字節不應該從流中移除,以便下一個'read'實際上會得到新的? – Onheiron 2016-07-04 08:35:32

2

base64String = Base64.encode(byteArray); 

全陣列(102400個字節)爲Base64,不只是你讀取的字節數轉換。你需要傳遞它的字節數。

1

new String(byteArray, 0, bytesRead);不修改數組。您需要使用System.arrayCopy將陣列修剪爲實際的數據大小。否則,你正在處理所有102400字節,其中大部分是零。

0

晚GraveDig ...只要你限制字節數組文件的大小。

FileInputStream fis = new FileInputStream(file); 
byte[] byteArray= new byte[(int) file.length()]; 
0

您可以使用File對象獲取文件的長度來初始化數組:

int length = Long.valueOf(file.length()).intValue(); 
byte[] byteArray = new byte[length]; 
0

您可以創建一個大陣,然後將其複製到使用System.arrayCopy一個新的數組

 int contentLength = 100000000; 
     byte[] byteArray = new byte[contentLength]; 

     BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream()); 
     while ((bytesRead = inputStream.read()) != -1) 
     { 
      byteArray[count++] = (byte)bytesRead; 
     } 

     byte[] destArray = new byte[count]; 
     System.arraycopy(byteArray, 0, destArray , 0, count); 

destArray將包含你想

0

的信息我知道這是一個老問題,但也許有人會發現我的代碼示例有用。此代碼在Base64中編碼文件,然後對其進行解碼並將其保存在新位置。

import java.io.IOException; 
import java.nio.file.Files; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import java.util.Arrays; 

import org.apache.commons.codec.binary.Base64; 

public class Base64Example { 

    public static void main(String[] args) { 

     Base64Example tempObject = new Base64Example(); 

     // convert file to regular byte array 
     byte[] codedFile = tempObject.convertFileToByteArray("your_input_file_path"); 

     // encoded file in Base64 
     byte[] encodedFile = Base64.encodeBase64(codedFile); 

     // print out the byte array 
     System.out.println(Arrays.toString(encodedFile)); 

     // print the encoded String 
     System.out.println(encodedFile); 

     // decode file back to regular byte array 
     byte[] decodedByteArray = Base64.decodeBase64(encodedFile); 

     // save decoded byte array to a file 
     boolean success = tempObject.saveFileFromByteArray("your_output_file_path", decodedByteArray); 

     // print out success 
     System.out.println("success : " + success); 
    } 

    public byte[] convertFileToByteArray(String filePath) { 

     Path path = Paths.get(filePath); 

     byte[] codedFile = null; 

     try { 
      codedFile = Files.readAllBytes(path); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return codedFile; 
    } 

    public boolean saveFileFromByteArray(String filePath, byte[] decodedByteArray) { 

     boolean success = false; 

     Path path = Paths.get(filePath); 

     try { 
      Files.write(path, decodedByteArray); 
      success = true; 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return success; 
    } 
}