Java 将 JPEG 转换为二进制(1 和 0)格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19738982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:50:07  来源:igfitidea点击:

Converting JPEG to binary (1 and 0) format

javapythonimage-processingjpeghuffman-code

提问by Meet

I want to convert a JPEG file into its binary equivalent and then convert it back to its JPEG form. i.e Convert a JPEG file into 1's and 0's and output this into a text file and then take this text file and convert it back to the original image (Just to check if there are no errors in conversion)

我想将 JPEG 文件转换为其二进制等效文件,然后将其转换回其 JPEG 格式。即将JPEG文件转换为1和0并将其输出为文本文件,然后将此文本文件转换回原始图像(只是为了检查转换中是否有错误)

I have tried doing this with binascii module in python, but there seems to be a problem of encoding that i cannot comprehend.

我曾尝试在 python 中使用 binascii 模块执行此操作,但似乎存在我无法理解的编码问题。

It would be really great if someone could help me out with this!

如果有人能帮我解决这个问题,那就太好了!

P.S: A solution in Java would be even more appreciated

PS:Java 中的解决方案会更受欢迎

回答by Tim Peters

Well, you'll be sorry ;-), but here's a Python solution:

好吧,你会很抱歉;-),但这里有一个 Python 解决方案:

def dont_ask(inpath, outpath):
    byte2str = ["{:08b}".format(i) for i in range(256)]
    with open(inpath, "rb") as fin:
        with open(outpath, "w") as fout:
            data = fin.read(1024)  # doesn't much matter
            while data:
                for b in map(ord, data):
                    fout.write(byte2str[b])
                data = fin.read(1024)

dont_ask("path_to_some_jpg", "path_to_some_ouput_file")

Of course this will convert anyfile to a file 8 times larger composed of "1" and "0" characters.

当然,这会将任何文件转换为由“1”和“0”字符组成的 8 倍大的文件。

BTW, I'm not writing the other half - but not because it's hard ;-)

顺便说一句,我不是在写另一半-但不是因为它很难;-)

回答by vandale

Java solution to convert any file (not just JPG) to binary:

将任何文件(不仅仅是 JPG)转换为二进制文件的 Java 解决方案:

    File input= new File("path to input");
    File output = new File("path to output");

    try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(input));
         BufferedWriter bw = new BufferedWriter(new FileWriter(output))) {
        int read;
        while ((read=bis.read()) != -1) {
              String text = Integer.toString(read,2);
              while (text.length() < 8) {
                    text="0"+text;
              }
              bw.write(text);
        }            
    } catch (IOException e) {
            System.err.println(e);
    }