PGM viewer Learn programming C#


File Management


PGM viewer


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).


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);

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

        string[] size;
        int width, height;

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

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

        // 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)
            else if (data[j] >= 100 || data[j] <= 149)
            else if (data[j] >= 50 || data[j] <= 99)
            else if (data[j] >= 0 || data[j] <= 49)


            if (amount % width == 0)

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.