正如標題所暗示的那樣,我試圖用Java編寫一個字節數組到一個bmp文件。目前,我的程序已成功將數據寫入文件位置,但它似乎缺少數據,因此無法打開。在下面列出的兩個功能中,目標是:將一個字節數組寫入一個bmp java
fromImage獲取灰度bmp圖像字節數據並將每個整數轉換爲二進制字符串,然後將其存儲在LinkedList節點中。 toImage接受該LinkedList,將二進制字符串轉換回整數,然後將新的字節數組寫回另一個文件。
public static LinkedList<String> fromImage(BufferedImage img) {
LinkedList<String> new_buff = new LinkedList<String>();
//try{
//img = ImageIO.read(new File("img/lena.bmp"));
byte[] byte_buffer = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
for(byte b : byte_buffer){
String buffer;
buffer = Integer.toBinaryString(b & 255 | 256).substring(1);
new_buff.addLast(buffer);
//System.out.println(buffer);
}
//}catch(IOException e){}
System.out.println("Exiting fromImage");
return new_buff;
}
// Save a binary number as a BMP image
// Image input hardcoded atm
public static BufferedImage toImage(LinkedList<String> bi) {
BufferedImage img = null;
int b;
byte[] bytes = new byte[bi.size()];
for(int i = 0; i < bi.size(); i++){
String temp = bi.get(i);
b = Integer.parseInt(temp);
bytes[i] = (byte) b;
//System.out.println(i);
}
System.out.println("Exiting For loop");
try{
Files.write(Paths.get("img/encrypted.bmp"), bytes);
//img = ImageIO.read(new File("img/lena.bmp"));
//ImageIO.write(img, "bmp", new File("img/encrypted.bmp"));
//img = ImageIO.read(new File("img/encrypted.bmp"));
}catch(IOException e){}
System.out.println("Exiting toImage");
return img;
}
所以,最後,我的問題是 - 哪裏是我缺少的數據,所以我錯過了它,我能做些什麼來解決這個問題?
什麼是通過'LinkedList'關於?你可以單元測試,這真的有效嗎(即可以正確地往返一個字節[]')? –
Thilo
我不是100%確定我明白你在問什麼,但是我將它作爲LinkedList存儲的原因是因爲從原始圖像中提取的像素字節是整數,我需要在最小有效位上進行更改二進制數字。 –
JustKeepSwimming