Programming Course in C# ¡Free!

PGM viewer

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

The PGM format is one of the versions NetPBM image formats. Specifically, is the variant that handles images in shades of gray.

Its header begins with a line containing P2 (if the image data are in ASCII) or P5 (if in binary).

The second line contains the width and height, separated by a space.

A third line containing the current value corresponding to the blank (typically 255, but could be 15 or other value).

From there begins the colors (shades of gray) of the points that form the image. In the ASCII format (P2) are numbers from 0-255 separated by spaces and line breaks perhaps. In the binary format (P5), are contiguous bytes, from 0 (black) to 255 (white).

You must create a program capable of reading a binary PGM file format (P5 header), without comment, with 255 shades of gray (but with a width and height that can vary). You must also represent colors (shades of gray) in console as follows:

• If the gray intensity is greater than 200, you will draw a blank.
• If it is between 150 and 199, you will draw a point.
• If you are between 100 and 149, you will draw a dash (-).
• If you are between 50 and 99, you will draw a symbol of "equal" (=).
• If you are between 0 and 49, you will draw a hash mark (#).

The name of the file to be analyzed must be read from the command line and not ask the user not be prefixed.

Note: line breaks (\ n) are represented by the ASCII character 10 (0x0A)

Output



Solution


using System;
using System.IO;

public class readerImagePGM
{     
public static void Main() 
{
// Read name file PGM
Console.WriteLine("Enter name of file PGM");
string name = Console.ReadLine();

// Read all data
FileStream filePGM = File.OpenRead(name);
byte[] data = new byte[filePGM.Length];
filePGM.Read( data, 0, filePGM.Length);
filePGM.Close();

// Read mesures file PGM
string mesures = "";
int i = 3;
do
{
mesures += Convert.ToChar(data[i]);
i++;
}
while(data[i]!=10);
i++;

string[] size;
int width, height;

size = mesures.Split(' ');
width = Convert.ToInt32( size[0] );
height = Convert.ToInt32( size[1] );

// Read color tone PGM
string colorTone = "";
do
{
colorTone += Convert.ToChar(data[i]);
i++;
}
while(data[i] != 10);
i++;

// Read pixels of PGM
int amount = 0;
for (int j = i; j < filePGM.Length; j++)
{
if (data[j] >= 200)
Console.Write(" ");
else if (data[j] >= 150 || data[j] <= 199)
Console.Write(".");
else if (data[j] >= 100 || data[j] <= 149)
Console.Write("-");
else if (data[j] >= 50 || data[j] <= 99)
Console.Write("=");
else if (data[j] >= 0 || data[j] <= 49)
Console.Write("#");

amount++;

if (amount % width == 0)
Console.WriteLine();
}
}
}