2013-11-02 71 views
-3

我想將JPEG文件轉換爲其二進制等效文件,然後將其轉換回其JPEG格式。 即將JPEG文件轉換爲1和0,並將其輸出到文本文件中,然後將該文本文件轉換回原始圖像(僅用於檢查轉換中是否存在錯誤)將JPEG轉換爲二進制(1和0)格式

我試過在python中用binascii模塊來做這件事,但似乎有一個我無法理解的編碼問題。

如果有人能幫助我,這將是非常好的!

PS:Java中的解決方案會更欣賞

+0

你說你想讓文本文件實際包含「0」和「1」字符?或者你的意思是別的嗎? –

+0

那麼你想要Java *還是Python?爲什麼Huffman Encoding標籤? – user2864740

+3

你究竟想要這樣做?從技術上講,JPEG文件已經是二進制文件。 –

回答

6

好了,你會後悔的;-),但這裏有一個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") 

當然,這將轉化任何文件轉換爲由「1」和「0」字符組成的文件的8倍。

順便說一句,我不寫的另一半 - 但不是因爲它很難;-)

+0

非常感謝您的幫助! – Meet

3

Java解決方案的任何文件(不只是JPG)轉換爲二進制:

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); 
    } 
相關問題