2011-07-15 63 views
2

我想將圖像和音頻文件轉換爲二進制流,然後對其進行處理,然後使用Java重構來自同一二進制流的圖像。我怎樣才能做到這一點?有人有過這方面的工作嗎?請儘快幫助我。任何提示或僞代碼將高度讚賞。 這是我試圖做到這一點,但它只是在重建圖像時創建一個空文件。 對於圖像二值: -在Java中將圖像和音頻文件轉換爲二進制

 File file = new File("E:\\image.jpg"); 
     BufferedImage img = ImageIO.read(file); 

     // write image to byte array in-memory (jpg format) 
     ByteArrayOutputStream b = new ByteArrayOutputStream(); 
     ImageIO.write(img, "jpg", b); 

     byte[] jpgByteArray = b.toByteArray(); 

     // convert it to a String with 0s and 1s 
     StringBuilder sb = new StringBuilder(); 
     for (byte by : jpgByteArray) { 
      sb.append(Integer.toBinaryString(by & 0xFF)); 

對於二進制圖像: -

 byte[] original = obj.orig_seq.getBytes(); 

     InputStream in = new ByteArrayInputStream(original); 
     BufferedImage img = ImageIO.read(in); 

     ImageIO.write(img, "jpg", 
       new File("E:\\mypic_new.jpg")); 

回答

2

要使用二進制字符串,你可以使用這個

StringBuilder sb = new StringBuilder(); 
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream("YourImage.jpg"))) { 
    for (int i; (i = is.read()) != -1;) { 
     String temp = "0000000" + Integer.toBinaryString(i).toUpperCase(); 
     if (temp.length() == 1) { 
      sb.append('0'); 
     } 
     temp = temp.substring(temp.length() - 8); 
     sb.append(temp).append(' '); 
    } 
} 
System.out.print(sb); 

,這裏是你想要的輸出

0000000 11111111 00000111 00011111 00101111 01111111

你也可以用十六進制,你的文件轉換成一個簡單的字符串是這樣的(建議)

StringBuilder sb = new StringBuilder(); 
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream("YourFile.txt"))) { 
    for (int i; (i = is.read()) != -1;) { 
     String temp = Integer.toHexString(i).toUpperCase(); 
     if (temp.length() == 1) { 
      sb.append('0'); 
     } 
     sb.append(temp).append(' '); 
    } 
} 
System.out.print(sb); 

,輸出會是這樣的

00 FF 07 1F 2F 7F 
相關問題