Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simple ASCII Art Generator

0.00/5 (No votes)
18 Jul 2007 1  
Uses less than 25 lines of code to convert a given picture to an equivalent ASCII picture
Screenshot - ASCII1.jpg

Introduction

This is a very simple program to convert a given picture into an ASCII Art of 1s & 0s. The output ASCII Image is saved in *.html format.

Using the Code

The code first reads the picture specified by the user into a bitmap object. Then it scans through each pixel of the image and converts it into its equivalent HTML tag, and saves the value into the output.html file.

The final output will look similar to the picture shown above.

StreamWriter sw = File.CreateText(outputPath);
Color color;
 
//Start of HTML file
sw.Write("<html> \n <body > \n <pre style=\"font: 10px/3px monospace;\">");

Random ran = new Random();
for (int y = 0; y < bmp.Height; y=y+3)
{
    for (int x = 0; x < bmp.Width; x=x+3)
    {
        int random = ran.Next(2);
        color = bmp.GetPixel(x, y);
        //write the HTML tag corresponding to the pixel color 
        //value of random will be either 1 or 0
        sw.Write("<span style=\"color: #{0:X2}{1:X2}{2:x2};\">{3}</span>", 
            (int)color.R, (int)color.G, (int)color.B, random);
    }

    sw.WriteLine("<br>");
}

//End of HTML file
sw.Write("</body>\n</html>");

sw.Close();

Note that we are using a random number generator to produce either 1 or 0 randomly.

int random = ran.Next(2);

Points of Interest

This is a very simple approach to creating color ASCII art. It will be quite simple to modify the above program to output other characters as well (rather than the 1 & 0 used here).

A sample picture created with a modified version of the above program could be found here.

Note: Sometimes, it may take several seconds for the background image to load.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here