【问题标题】:Converting JPEG to binary (1 and 0) format [closed]将JPEG转换为二进制(1和0)格式[关闭]
【发布时间】:2013-11-13 09:00:16
【问题描述】:

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

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

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

P.S:Java 中的解决方案将更加感激

【问题讨论】:

  • 您是说您希望文本文件实际包含“0”和“1”字符吗?还是你的意思是别的?
  • 那么你想要Java 还是 Python?为什么要使用 Huffman Encoding 标签?
  • 你到底想要这个做什么?从技术上讲,JPEG 文件已经是二进制文件了。
  • @DavidWallace 是的,文本文件应该包含实际的 0 和 1 字符作为 JPEG 二进制代码的表示
  • @ChristianTernus 是的,我明白这一点。我只是希望该二进制表示为“1”和“0”字符

标签: java python image-processing jpeg huffman-code


【解决方案1】:

好吧,你会很抱歉 ;-),但这里有一个 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")

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

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

【讨论】:

  • 非常感谢您的帮助!
【解决方案2】:

将任何文件(不仅仅是 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);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    相关资源
    最近更新 更多