Display BPM On Console - C# Programming Exercise

This exercise involves creating a C# program to decode an image file in the Netpbm format (specifically, the P1 format, which is for black and white images encoded in ASCII) and display it on the console. The input file may contain a header with "P1", an optional comment, and the image dimensions followed by data represented by "1" for black pixels and "0" for white pixels. The program should read this data and display the image on the console using characters to represent the pixels, such as "X" for black pixels and " " (space) for white pixels. This exercise teaches how to read and process text formatted files and work with the console in C#.

 Category

File Management

 Exercise

Display BPM On Console

 Objective

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 black and white 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 and 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 the screen using only the console. Remember that the comment is optional.

 Write Your C# Exercise

// Import the System namespace for basic input/output operations
using System;  

// Import the System.IO namespace for file operations
using System.IO;  

// Declare the main Program class
class Program
{
    // Main method where the program starts
    static void Main()
    {
        // Specify the path to the PBM image file
        string filePath = "j.pbm";  // Replace this with the path to your PBM file

        // Try to read and display the PBM file content
        try
        {
            // Open the file using StreamReader to read text from the PBM file
            using (StreamReader reader = new StreamReader(filePath))
            {
                // Read the first line, which should be "P1" (PBM header)
                string header = reader.ReadLine();  
                if (header != "P1")  // Check if the header is "P1"
                {
                    Console.WriteLine("Invalid PBM format. Expected 'P1'.");
                    return;  // Exit the program if the header is not correct
                }

                // Read the optional comment line (skip it)
                string commentLine = reader.ReadLine();
                while (commentLine.StartsWith("#"))  // Check if the line starts with "#"
                {
                    commentLine = reader.ReadLine();  // Read the next line if it's a comment
                }

                // Read the width and height of the image
                string[] dimensions = commentLine.Split(' ');  // Split the dimensions by space
                int width = int.Parse(dimensions[0]);  // First element is the width
                int height = int.Parse(dimensions[1]);  // Second element is the height

                // Print a message to inform the user about the image size
                Console.WriteLine($"Image dimensions: {width} x {height}");

                // Loop through each row of pixels and print it to the console
                for (int y = 0; y < height; y++)  // Loop through each row
                {
                    // Read the next line, which contains the pixel data for the row
                    string row = reader.ReadLine();  
                    string[] pixels = row.Split(' ');  // Split the row into individual pixel values

                    // Loop through each pixel in the row
                    for (int x = 0; x < width; x++)  // Loop through each pixel in the row
                    {
                        // Check the pixel value: 0 means white, 1 means black
                        if (pixels[x] == "1")  
                        {
                            Console.Write("X");  // Display 'X' for black pixels
                        }
                        else
                        {
                            Console.Write(" ");  // Display a space for white pixels
                        }
                    }
                    Console.WriteLine();  // Move to the next line after printing the row
                }
            }
        }
        catch (Exception ex)  // Catch any errors that may occur during file reading
        {
            // Print the error message to the console
            Console.WriteLine($"Error reading the file: {ex.Message}");
        }
    }
}

 Share this C# exercise

 More C# Programming Exercises of File Management

Explore our set of C# programming 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#.

  •  PCX width and height

    This exercise involves creating a C# program to check if a file is a PCX image and, if so, extract and display the image's dimensions (width and height). To do...

  •  Extract text from a binary file

    This exercise involves creating a C# program that extracts only the alphabetic characters contained in a binary file and dumps them to a separate file. The program sh...

  •  C# to Pascal converter

    This exercise involves creating a C# program that converts simple C# programs to their equivalent in the Pascal language. The program should read C# cod...

  •  Dump

    This exercise involves creating a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes per row and 24 rows per screen. The program should pause a...

  •  DBF extractor

    This exercise involves creating a program that displays the list of fields stored in a DBF file. The DBF format is used by the old dBase database manager and is still suppor...

  •  Text censorer

    This exercise involves creating a program to censor text files. The program should read a text file and output its contents to a new file, replacing certain words with "[CEN...