Exercise
Display BPM on console
Objetive
The Netpbm format is a family of image file formats designed with simplicity in mind, rather than small size. They can represent color, grayscale, or black and white images using plain text (even though a binary variant exists).
For example, a black and white image coded in ASCII is represented using the header "P1".
The following line (optional) might be a comment, preceded with #.
The next line contains the width and height of the image.
The remaining line(s) contain the data: 1 for black points and 0 for white points, as in this example:
P1
This is an example bitmap of the letter "J"
6 10
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
1 0 0 0 1 0
0 1 1 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0
(that would be the content of a file named "j.pbm").
Create a program to decode an image file like this and display it on the screen using only the console. Remember that the comment is optional.
Example Code
import java.util.*;
public class Main
{
public static void main(String[] args)
{
String fileName;
String data;
String line;
int width;
int height;
System.out.println("Enter the file name: ");
fileName = new Scanner(System.in).nextLine();
if (!fileName.contains(".pbm"))
{
fileName += ".pbm";
}
if (!(new java.io.File(fileName)).isFile())
{
System.out.println("File not found!");
return;
}
// File reading
try
{
java.io.FileReader myFile = new java.io.FileReader(fileName);
java.io.BufferedReader myFileBufferedReader = new java.io.BufferedReader(myFile);
line = myFileBufferedReader.readLine();
if (!line.equals("P1"))
{
System.out.println("Does not seem a B&W ASCII PBM");
return;
}
System.out.println("Found B&W ASCII PBM");
// Width and height
line = myFileBufferedReader.readLine();
if ((line.length() > 1) && (line.charAt(0) == '#'))
{
System.out.println("Comment: " + line.substring(1));
line = myFileBufferedReader.readLine();
}
String[] widthheight = line.split("[ ]", -1);
width = Integer.parseInt(widthheight[0]);
height = Integer.parseInt(widthheight[1]);
System.out.printf("width: %1$s" + "\r\n", width);
System.out.printf("height: %1$s" + "\r\n", height);
// Data reading (gathering all the lines in one)
data = "";
line = myFileBufferedReader.readLine();
while (line != null)
{
data += line;
line = myFileBufferedReader.readLine();
}
myFile.close();
}
catch (IOException problem)
{
System.out.println("File was not read properly");
System.out.printf("Details: %1$s" + "\r\n", problem.getMessage());
return;
}
// Delete spaces, so that ony 0 and 1 remain
data = data.replace(" ", "");
// And traversing the data, displaying them
int pos = 0;
for (char symbol : data)
{
// After the width, we must advance to the next line
if (pos % width == 0)
{
System.out.println();
}
if (symbol == '1')
{
System.out.print("X");
}
else if (symbol == '0')
{
System.out.print(".");
}
pos++;
}
System.out.println();
}
}