As the title suggests, I'm attempting to write a byte array to a bmp file in Java. Currently, my program successfully writes data to the file location, however it appears to be missing data and cannot be opened because of it. Of the two functions listed below the goal is:
fromImage takes a grayscale bmp image byte data and converts each integer to a binary string, which is then stored in a LinkedList node. toImage takes that LinkedList, converts the binary strings back to integers and then writes the new byte array back to another file.
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;
}
So ultimately, my question is - Where is the data I'm missing, why am I missing it, and what can I do to fix it?
LinkedList<String>about? Can you unit-test that this really works (i.e. can round-trip abyte[]properly)?