Odczyt pliku BMP w trybie binarnym

0

Napisałem kod do odczytu plików w trybie binarnym, testuję go na pliku bmp o wymiarach 2px2px(1 - kolor biały, 0 kolor czarny)*

Obrazek ma taki rozkład kolorów:
0 1
1 0

Kod źródłowy:

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class BinaryInputFile {
	private File file;
	private byte[] bin;
	
	public BinaryInputFile(String pathname) {
		file = new File(pathname);
	}
	
	public void getFile() {
		try {
			FileInputStream fpIn = new FileInputStream(file);
			DataInputStream fp = new DataInputStream(fpIn);
			
			int counter = 0;
			while(true) {
				try {
					System.out.print(fp.readByte() + " ");					
					counter++;
				} catch(IOException ex) {
					System.err.println("Drukowanie: " + ex);
					try {
						fp.close();
					} catch(IOException exc) {
						System.err.println(exc);
					}
					break;
				}
			}
		} catch(FileNotFoundException ex) {
			System.err.println(ex);
		}
	}
}

W wyniku otrzymuję:

66 77 70 0 0 0 0 0 0 0 54 0 0 0 40 0 0 0 2 0 0 0 2 0 0 0 1 0 24 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 -1 -1 0 0 0 0 0 0 0 0 -1 -1 -1 0 0 Drukowanie: java.io.EOFException

I teraz mam pytania:

  1. Czy w dobry sposób odczytuję bity z pliku?
  2. Co oznaczają liczby większe od 1, a co oznacza wartość 0 oraz -1

EDIT:
Zmieniłem kod na taki:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class BinaryInputFile {
	private File file;
	private byte[] bin;
	
	public BinaryInputFile(String pathname) {
		file = new File(pathname);
	}
	
	public void getFile() {
		try {
			RandomAccessFile fp = new RandomAccessFile("D:/a.bmp", "r");
			long pointer = 0;
			int counter = 0;
			try { 
				fp.seek(0);
				while(pointer < fp.length()) {
					System.out.print(fp.readUnsignedByte() + " ");
					pointer = fp.getFilePointer();
					counter++;
				}
				fp.close();
				System.out.println("\n" + counter);
			} catch(IOException exc) {
				System.err.println("IOException: " + exc);
			}
		} catch(FileNotFoundException ex) {
			System.err.println("Plik nieodnaleziony");
		}
	}
}

Wynik jaki otrzymuję:

66 77 70 0 0 0 0 0 0 0 54 0 0 0 40 0 0 0 2 0 0 0 2 0 0 0 1 0 24 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 255 255 255 0 0 0 0 0 0 0 0 255 255 255 0 0

Od liczby 255 zaczyna się malowanie obrazka, cała reszta przed pierwszą wartością 255 to nagłówki. Nasuwa mi się pytanie czy nagłówki zawsze wynoszą 54 bajty?

0

Nie zastanawialem sie nad odpowiedzia, wiem jedynie ze Twoj kod powinien uzywac InputStreama a nie RandomAccessFile, skoro czytasz plik sewkencyjnie.

0

Tutaj masz trochę na temat specyfikacji formatu bmp: http://en.wikipedia.org/wiki/BMP_file_format#File_structure

0

Dopisałem już do mojej aplikacji odczyt i zapis tekstu do pliku BMP, jednakże po zapisaniu informacji w pliku jego waga zwiększa się prawie dwukrotnie, a otworzenie jego za pomocą dowolnej przeglądarki plików graficznych staje się niemożliwe.

Dodam jeszcze, że nagłówki pliku nie są modyfikowane tylko bajty odpowiadające za kolory.

Główna klasa do obsługi plików BMP

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class BinaryInputFile {
	private final static int BMP_HEADER = 54;
	
	RandomAccessFile fp;
	int[][] binary;
	int[] buffer;
	
	
	public BinaryInputFile() {}
	
	public void open(String filename) {
		try {
			fp = new RandomAccessFile(filename, "r");
			try {
				int len = (int)fp.length();
				int pointer = 0;
				buffer = new int[len];
				
				while(pointer < len) {
					buffer[pointer] = fp.readUnsignedByte(); System.out.print(buffer[pointer] + " ");
					pointer++;
				}
				
				convertDecToBin();
				fp.close();
			} catch(IOException exc) {
				System.err.println(exc);
			}			
		} catch(FileNotFoundException ex) {
			System.err.println("File not found: " + ex);
		}
	}
	
	/**
	 * Saving message into BMP file
	 * @param filename
	 * @param msg
	 */
	public void save(String filename, String msg) {
		try {
			fp = new RandomAccessFile(filename, "rw");
			try {
				int len = (int)fp.length();
				int pointer = 0;
				buffer = new int[len];
				
				while(pointer < len) {
					buffer[pointer] = fp.readUnsignedByte();
					pointer++;
				}
				
				AsciiConverter ascii = new AsciiConverter(msg);
				int[][] asciiDec = ascii.get();
				
				int[][] newFp = hide(asciiDec, convertDecToBin());
				
				/* Write new data */
				fp.seek(0);
				String out = "";
				int pow = 7;
				for(int i = 0; i < newFp.length; i++) { 
					if(i >= BMP_HEADER) {
						int temp = 0;
						for(int j = 0; j < newFp[i].length; j++) { 
							temp += newFp[i][j]*((int)(Math.pow((double)2, (double)pow)));
							if(pow > 0)
								pow--;
							else 
								pow = 7;
						}
						buffer[i] = temp;	
					}
					out += buffer[i];
				}				
				
				fp.writeBytes(out);
				fp.close();
			} catch(IOException exc) {
				System.err.println(exc);
			}
		} catch(FileNotFoundException ex) {
			System.err.println("File not found: " + ex);
		}
	}
	
	/**
	 * Convert decimal to binary
	 * @return Integer[][]
	 */
	private int[][] convertDecToBin() {
		int[][] binary = new int[buffer.length][8];
		
		for(int i = BMP_HEADER; i < buffer.length; i++) {
			int j = 7;
			int rest = 0;
			while(j >= 0) {
				rest = buffer[i] % 2;
				buffer[i] = buffer[i] / 2;
				if(rest == 0)
					binary[i][j] = 0;
				else if(rest == 1)
					binary[i][j] = 1;		
				j--; 
			}			
		}

		return binary;
	}
	
	/**
	 * Hide code into BMP file
	 */
	private int[][] hide(int[][] code, int[][] bmp) {
		int counter = 0;
		int j = 0;
		for(int i = BMP_HEADER; i < bmp.length; i++) {
			bmp[i][7] = code[counter][j]; 
			if(j < 7) {
				j++;
			} else {
				j = 0;
				if(counter < (code.length - 1))
					counter++;
				else
					break;
			}			
		}
		
		return bmp;
	}
}

Klasa konwertująca znaki ASCII na liczby binarne

public class AsciiConverter {
	int[] ascii = { 
					'1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
					'~', '`', '!', '@', '#', '$', '%', '^', '&', '*',
					'(', ')', '_', '-', '=', '+', '[', ']', '{', '}',
					'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p',
					'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z',
					'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R',
					'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F',
					'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B',
					'N', 'M', ';', ':', '"', '\'', '\\', '?', '/', '<',
					'>', ',', '.'
				  };
	int[][] binary;
	char[] msg;
	
	
	public AsciiConverter(String msg) {
		this.msg = msg.toCharArray();
		convertDecToBin();
	}
	
	/**
	 * Convert char to decimal
	 * @return Integer[]
	 */
	private int[] convertCharToDec() {
		int[] buffer = new int[msg.length];
		
		for(int i = 0; i < msg.length; i++) {
			for(int j = 0; j < ascii.length; j++) {
				if(ascii[j] == ((int)msg[i])) 
					buffer[i] = (int)msg[i];
			} 
		}
		
		return buffer;
	}
	
	/**
	 * Convert decimal to binary
	 */
	private void convertDecToBin() {
		int[] buffer = convertCharToDec();
		binary = new int[buffer.length][8];
		
		for(int i = 0; i < buffer.length; i++) {
			int j = 7;
			int rest = 0;
			while(j >= 0) {
				rest = buffer[i] % 2;
				buffer[i] = buffer[i] / 2;
				if(rest == 0)
					binary[i][j] = 0;
				else if(rest == 1)
					binary[i][j] = 1;				
				j--;
			}			
		}
	}
	
	/**
	 * Created binary matrix from string
	 * @return Integer[][]
	 */
	public int[][] get() {
		return binary;
	}
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1