Proposed exercise
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 BW 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 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 screen, using just the console. Remember that the comment is optional.
Output
Solution
using System;
using System.IO;
class ReadPBM
{
public static void Main()
{
Console.WriteLine("Enter the name: " );
string name = Console.ReadLine();
if ( ! name.Contains(".pbm"))
name += ".pbm";
if (!File.Exists( name ))
{
Console.WriteLine( "File not found!");
return;
}
try
{
string data = "";
StreamReader file = File.OpenText(name);
int width, height;
string line = file.ReadLine();
if (line != "P1")
{
Console.WriteLine("format of image not valid");
return;
}
line = file.ReadLine();
if ((line.Length > 1) && (line[0] == '#'))
{
Console.WriteLine("Comment: "
+ line.Substring(1));
line = file.ReadLine();
}
string [] mesures = line.Split(' ');
width = Convert.ToInt32(mesures[0]);
height = Convert.ToInt32(mesures[1]);
Console.WriteLine("Width: {0} px - Height: {1} px", width, height);
line = file.ReadLine();
while (line != null)
{
data += line;
line = file.ReadLine();
}
file.Close();
}
catch (xception)
{
Console.WriteLine("Error");
return;
}
data = data.Replace(" ","");
int position = 0;
foreach (char symbol in data)
{
if (position % width == 0)
Console.WriteLine();
if (symbol == '1')
Console.Write("X");
else if (symbol == '0')
Console.Write(".");
position ++;
}
}
}