我在將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碼寫入。
這裏是輸出的(小)部分:
return Utils.toImage("R0lGODlhEAALANUAANPTAPZva/n5AfLySPz8iYqY3O01NgoksbGZa+kYGOskJKi05vb2XZ+r4+05O"<tab>+"Pv7eO3tKPv7bZak4dSvebC76tC2iPNISPX1UMkAAMm6U/NWTeYAAF5y1LqlevNaWpSh3e7uQ+1CQ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AAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>
感謝。
編輯:我使用的base64編碼從這樣一個問題:https://stackoverflow.com/a/4265472/1295422
你可以粘貼來自Utils類的toImsge的代碼 – UVM 2012-04-19 10:22:39
你是否將圖像作爲整個字節數組傳遞給Base64編碼器? – 2012-04-19 10:23:02