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
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Please provide a PGM file name as a command-line argument.");
return;
}
string filePath = args[0];
using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
{
string header = new string(reader.ReadChars(2));
if (header != "P5")
{
Console.WriteLine("Invalid PGM format. This program only supports binary PGM (P5) format.");
return;
}
string line;
do
{
line = ReadLine(reader);
} while (line.StartsWith("#"));
string[] dimensions = line.Split(' ');
int width = int.Parse(dimensions[0]);
int height = int.Parse(dimensions[1]);
int maxIntensity = int.Parse(ReadLine(reader));
byte[] pixels = reader.ReadBytes(width * height);
int pixelIndex = 0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int intensity = pixels[pixelIndex++];
char displayChar = MapIntensityToChar(intensity);
Console.Write(displayChar);
}
Console.WriteLine();
}
}
Console.WriteLine("PGM file has been processed and displayed.");
}
static string ReadLine(BinaryReader reader)
{
string line = "";
char c;
while ((c = reader.ReadChar()) != '\n')
{
line += c;
}
return line.Trim();
}
static char MapIntensityToChar(int intensity)
{
if (intensity > 200) return ' ';
if (intensity >= 150) return '.';
if (intensity >= 100) return '-';
if (intensity >= 50) return '=';
return '#';
}
}
Output
# . - =
= # . .
. - = #