Exercise
PGM viewer
Objetive
The PGM format is one of the versions of NetPBM image formats. Specifically, it is the variant capable of handling images in shades of gray.
Its header begins with a line containing P2 (if the image data is in ASCII) or P5 (if it is in binary).
The second line contains the width and height, separated by a space.
A third line contains the intensity value that corresponds to the target (typically 255, although it could also be 15 or another value).
From there, the colors (shades of gray) of the points that make up the image begin. In ASCII format (P2), they are numbers from 0 to 255 separated by spaces and perhaps newlines. In binary (P5) format, they are contiguous bytes, from 0 (black) to 255 (white).
You must create a program capable of reading a file in binary PGM format (header P5), without comments, with 255 shades of gray (but with a width and height that can vary). In addition, you must represent the colors (shades of gray) in the console as follows:
If the intensity of gray is greater than 200, you will draw a blank space.
If it is between 150 and 199, you will draw a point.
If it is between 100 and 149, you will draw a dash (-).
If it is between 50 and 99, you will draw an "equals" symbol (=).
If it is between 0 and 49, you will draw a pound sign (#).
The name of the file to be analyzed must be read from the command line, not prompted by the user or pre-set.
Note: line breaks (\n) are represented by character 10 of the ASCII code (0x0A).
Example Code
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Read name file PGM
System.out.println("Enter name of file PGM");
String name = new Scanner(System.in).nextLine();
// Read all data
java.io.FileInputStream filePGM = File.OpenRead(name);
byte[] data = new byte[filePGM.getLength()];
filePGM.read(data, 0, filePGM.getLength());
filePGM.close();
// Read mesures file PGM
String mesures = "";
int i = 3;
do
{
mesures += (char)data[i];
i++;
} while (data[i] != 10);
i++;
String[] size;
int width, height;
size = mesures.split("[ ]", -1);
width = Integer.parseInt(size[0]);
height = Integer.parseInt(size[1]);
// Read color tone PGM
String colorTone = "";
do
{
colorTone += (char)data[i];
i++;
} while (data[i] != 10);
i++;
// Read pixels of PGM
int amount = 0;
for (int j = i; j < filePGM.getLength(); j++)
{
if (data[j] >= 200)
{
System.out.print(" ");
}
else if (data[j] >= 150 || data[j] <= 199)
{
System.out.print(".");
}
else if (data[j] >= 100 || data[j] <= 149)
{
System.out.print("-");
}
else if (data[j] >= 50 || data[j] <= 99)
{
System.out.print("=");
}
else if (data[j] >= 0 || data[j] <= 49)
{
System.out.print("#");
}
amount++;
if (amount % width == 0)
{
System.out.println();
}
}
}
}