Image to ASCII art in C# (why not?)
Creating ASCII art from an image involves converting the pixels of the image into appropriate ASCII characters based on their luminance or brightness. Here’s a basic implementation of this idea in C#
- First, you’ll need the .NET Core SDK installed on your machine.
- Create a new console project:
dotnet new console -n ImageToAscii
cd ImageToAscii
Add the required package for image processing:
dotnet add package SixLabors.ImageSharp
We are using top-level statements (less clutter):
using System;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
if (args.Length == 0)
{
Console.WriteLine("Please provide the path to an image.");
return;
}
string path = args[0];
ConvertImageToAscii(path);
void ConvertImageToAscii(string imagePath)
{
using var image = Image.Load<Rgba32>(imagePath);
char[] asciiChars = { '@', '#', '8', '&', 'o', ':', '*', '.', ' ' };
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
Rgba32 pixelColor = image[x, y];
float avg = (pixelColor.R + pixelColor.G + pixelColor.B) / 3.0f;
int index = (int)(avg * (asciiChars.Length - 1) / 255);
Console.Write(asciiChars[asciiChars.Length - index - 1]);
}
Console.WriteLine();
}
}
To run just pass the full path of the image and the ASCII art will be printed on the console (use smaller images for better results).
dotnet run [path_to_your_image]