24

我在将 gif 图像转换为 base 64 字符串时遇到问题。

当我转换它时,代码加了我 100,000 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;
    }
}

基本上,它在一个文本文件中写入out.txt了一堆 java 方法,其中包含 base 64 代码。

这是输出的(小)部分:

return Utils.toImage("R0lGODlhEAALANUAANPTAPZva/n5AfLySPz8iYqY3O01NgoksbGZa+kYGOskJKi05vb2XZ+r4+05O"<tab>+"Pv7eO3tKPv7bZak4dSvebC76tC2i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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<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

4

8 回答 8

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

无论您在数组中实际使用多少数据,该代码都将编码 102400 个字节。

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

您需要在某处使用 bytesRead 的值。

此外,这可能不会一次性将整个文件读入数组(它只读取 I/O 缓冲区中的内容),因此您的循环可能无法正常工作,您最终可能会在数组中得到一半的图像.

我会在这里使用 Apache Commons IOUtils:

 Base64.encode(FileUtils.readFileToByteArray(file));
于 2012-04-19T10:24:57.073 回答
5

首先,这行代码:

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

相当于

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

所以它是从偏移量 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);

或者像 Thilo 使用 FileUtils 那样进一步压缩它。

于 2012-04-19T10:23:42.953 回答
2

线

base64String = Base64.encode(byteArray);

将整个数组(102400 字节)转换为 Base64,而不仅仅是您读取的字节数。您需要将字节数传递给它。

于 2012-04-19T10:24:12.797 回答
1

new String(byteArray, 0, bytesRead);不修改数组。您需要使用System.arrayCopy将数组修剪为实际数据大小。否则,您将处理所有 102400 字节,其中大部分是零。

于 2012-04-19T10:24:33.223 回答
0

Late GraveDig ...只需将您的字节数组限制为文件大小。

FileInputStream fis = new FileInputStream( file );
byte[] byteArray= new byte[(int) file.length()];
于 2014-03-07T03:01:22.667 回答
0

您可以使用文件对象来获取文件的长度来初始化您的数组:

int length = Long.valueOf(file.length()).intValue();
byte[] byteArray = new byte[length];
于 2014-04-04T05:44:33.767 回答
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 将包含您想要的信息

于 2014-04-08T03:55:49.550 回答
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;
    }
}
于 2017-02-17T01:49:18.297 回答