PGM Image Parser and Console Display in C#

This program reads a PGM image file in binary format (P5) and represents its shades of gray in the console using different characters based on the intensity value. The program first processes the header of the PGM file, extracting the width, height, and maximum intensity value. Then, it reads the pixel values and displays them in the console using specific symbols for different intensity ranges. The mapping is as follows:

- Intensity > 200: blank space
- Intensity between 150 and 199: point (.)
- Intensity between 100 and 149: dash (-)
- Intensity between 50 and 99: equals sign (=)
- Intensity between 0 and 49: pound sign (#)

The file name should be provided via the command line, and the program will automatically process and display the image using these representations.



Group

File Handling in C#

Objective

1. Read the PGM file in binary format (P5) from the command line argument.
2. Parse the header to retrieve the image's width, height, and maximum intensity value.
3. Read the pixel values (shades of gray) and map each pixel intensity to a specific character.
4. Output the image representation to the console.
5. Ensure that the program can handle varying image sizes and shades of gray.

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.

Example C# Exercise

 Copy C# Code
using System;
using System.IO;

class PGMParser
{
    // Main method to execute the program
    static void Main(string[] args)
    {
        // Check if the user has provided a file name as a command-line argument
        if (args.Length == 0)
        {
            Console.WriteLine("Please provide a PGM file name as a command-line argument.");
            return;
        }

        // Define the file path from the command-line argument
        string filePath = args[0];

        // Open the PGM file for reading in binary mode
        using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
        {
            // Read the header (first line is P5)
            string header = new string(reader.ReadChars(2)); // "P5"
            if (header != "P5")
            {
                Console.WriteLine("Invalid PGM format. This program only supports binary PGM (P5) format.");
                return;
            }

            // Skip comments (if any) and read the width and height from the next line
            string line;
            do
            {
                line = ReadLine(reader);
            } while (line.StartsWith("#")); // Ignore comment lines

            // Read the width and height from the header
            string[] dimensions = line.Split(' ');
            int width = int.Parse(dimensions[0]);
            int height = int.Parse(dimensions[1]);

            // Read the maximum intensity value (usually 255)
            int maxIntensity = int.Parse(ReadLine(reader));

            // Read the pixel values (shades of gray)
            byte[] pixels = reader.ReadBytes(width * height);

            // Process and display the image in the console
            int pixelIndex = 0;
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    // Get the intensity of the current pixel
                    int intensity = pixels[pixelIndex++];

                    // Map the intensity to a specific character
                    char displayChar = MapIntensityToChar(intensity);

                    // Output the character to the console
                    Console.Write(displayChar);
                }
                // Move to the next line after each row of pixels
                Console.WriteLine();
            }
        }

        // Notify the user that the operation is complete
        Console.WriteLine("PGM file has been processed and displayed.");
    }

    // Helper method to read a line from the file
    static string ReadLine(BinaryReader reader)
    {
        string line = "";
        char c;
        while ((c = reader.ReadChar()) != '\n') // Read until newline character
        {
            line += c;
        }
        return line.Trim();
    }

    // Helper method to map intensity to corresponding character
    static char MapIntensityToChar(int intensity)
    {
        if (intensity > 200) return ' ';
        if (intensity >= 150) return '.';
        if (intensity >= 100) return '-';
        if (intensity >= 50) return '=';
        return '#';
    }
}

 Output

# . - =
= # . .
. - = #

Share this C# Exercise

More C# Practice Exercises of File Handling in C#

Explore our set of C# Practice Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.