Grupo
Manejo de archivos en C#
Objectivo
1. Lea el archivo PGM en formato binario (P5) desde el argumento de la línea de comandos.
2. Analice el encabezado para obtener el ancho, la altura y el valor máximo de intensidad de la imagen.
3. Lea los valores de los píxeles (tonos de gris) y asigne la intensidad de cada píxel a un carácter específico.
4. Envíe la representación de la imagen a la consola.
5. Asegúrese de que el programa pueda gestionar diferentes tamaños de imagen y tonos de gris.
El formato PGM es una de las versiones de los formatos de imagen NetPBM. Específicamente, es la variante capaz de gestionar imágenes en tonos de gris.
Ejemplo de ejercicio en C#
Mostrar código C#
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
# . - =
= # . .
. - = #
Código de ejemplo copiado
Comparte este ejercicio de C#