Display BPM on console C# Exercise - C# Programming Course

 Lesson

File Management

 Exercise

Display BPM on console

 Objetive

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.

 Example Code

// 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}");
        }
    }
}

More C# Exercises of File Management

 Writing to a text file
Create a program to ask the user for several sentences (until they just press Enter) and store them in a text file named "sentences.txt"...
 Appending to a text file
Create a program to ask the user for several sentences (until they just press Enter) and store them in a text file named "sentences.txt". If the file ...
 Display file contents
Create a program to display all the contents of a text file on screen (note: you must use a StreamReader). The name of the file will be entered in the...
 Extended TextToHTML (files)
Expand the TextToHtml class, so that ir can dump it result to a text file. Create a method ToFile, which will receive the name of the file as a parame...
 Logger
Create a class Logger, with a static method Write, which will append a certain text to a file: Logger.Write("myLog.txt", "This text is being logged");...
 More
Create a program which behaves like the Unix command "more": it must display the contents of a text file, and ask the user to press Enter each time th...
 Text replacer
Create a program to replace words in a text file, saving the result into a new file. The file, the word to search and word to replace it with must ...
 Count letters in a file
Create a program to count the amount of times that a certain character is inside a file (of any kind). The file and the letter can be asked to the ...
 Reading a binary file (1: BMP)
Create a C# program to check if a BMP image file seems to be correct. It must see if the first two bytes are B and M (ASCII codes 0x42 and 0x4D). ...
 Writing to a binary file
Create a program which asks the user for his name, his age (byte) and the year in which he was born (int) and stores them in a binary file. Create ...
 C# to Java
Create a basic C# to Java translator. It must accept a C# source files, and create an equivalent Java source file. It will receive the file name in...
 Invert a text file
Create a program to "invert" the contents of a text file: create a file with the same name ending in ".tnv" and containing the same lines as the origi...
 Reading a binay file (2 - GIF)
Create a C# program to check if a GIF image file seems to be correct. It must see if the first four bytes are G, I, F, 8. In case it seems corre...
 Friends database, using files
Expand the "friends database", so that it loads data from file at the beginning of each session (if the file exists) and saves the data to file when t...
 Pascal to C# translator
Create a basic Pascal to C# translator. It will accept program such as: example program; var i: integer; max: integer; begin writeLn("How ...
 Convert a text file to uppercase
Write a program to read a text file and dump its content to another file, changing the lowercase letters to uppercase. You must deliver only the "....
 Convert any file to uppercase
Write a program to read a file (of any kind) and dump its content to another file, changing the lowercase letters to uppercase. You must deliver on...
 File inverter
Create a program to "invert" a file: create a file with the same name ending in ".inv" and containing the same bytes as the original file but in rever...
 File encrypter
Create a program to encrypt a text file into another text file....
 Count words
Create a C# program to count the amount of words stored in a text file...
 BMP width and height, BinaryReader
Create a C# program to display the width and height of a BMP file using a BinaryReader. The structure of the header of a BMP file is: File type ...
 TXT to HTML translator
Create a "Text to HTML converter", which will read a source text file and create a HTML file from its contents. For example, if the file contains: Ho...
 Invert binary file V2
Create a program to "invert" a file using a "FileStream". The program should create a file with the same name ending in ".inv" and containing the same...
 BMP width & height, FileStream
Create a C# program to display the width and height of a BMP file using a FileStream. Remember the structure of the BMP header: File type (lette...
 File copier
Create a program to copy a source file to a destination file. You must use FileStream and a block size of 512 KB. An example usage might be: mycopy...
 MP3 reader
ID3 specifications apply to any file or audiovisual container, but they are primarily used with audio containers. There are three compatible versions ...
 C to C# converter
Create a program to convert simple C programs, such as the following one, to C#: Note: the resulting program must compile correctly. Test it with oth...
 File splitter
Create a program to split a file (of any kind) into pieces of a certain size. It must receive the name of the file and the size as parameters. For exa...
 Encrypt a BMP file
Create a program to encrypt/decrypt a BMP image file by changing the "BM" mark in the first two bytes to "MB" and vice versa. Use the advanced File...
 CSV converter
The CSV ("Comma Separated Values") is an exchange format used by many spreadsheet and database management systems. It consists of a series of comma-se...
 File comparer
Create a C# program to tell if two files (of any kind) are identical (have the same content)....
 PCX width and height
Create a program that checks if a file is a PCX image and, if so, displays its width and height using the following specification: What is the PCX ...
 Extract text from a binary file
Create a program that extracts only the alphabetic characters contained in a binary file and dumps them to a separate file. The extracted characters s...
 C# to Pascal converter
Create a program that converts simple C# programs, such as the following one, to the Pascal language....
 Dump
Create a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes in each row and 24 rows in each screen. The program should p...
 DBF extractor
Create 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 suppo...
 Text censorer
Create a program to censor text files. It should read a text file and dump its results to a new text file, replacing certain words with "[CENSORED]". ...
 SQL to text
You must create a C# program that is capable of parsing SQL INSERT commands and extracting their data into separate lines of text, as follows. If the ...
 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 he...
 Display BMP on console V2
Create a program to display a 72x24 BMP file on the console. You must use the information in the BMP header (refer to the exercise of Feb. 7th). Pay a...

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