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
Show 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
# . - =
= # . .
. - = #