ASCII Art Generator in Java
Join the DZone community and get the full member experience.Join For Free
ascii art is a technique that uses printable characters from ascii standard to produce visual art. it had it’s purpose in history when printers lacked graphics ability and it was also used in emails when embedding images was yet not possible. i present you a very simple ascii art generator written in java with configurable font and contrast. since it was built over a few hours during the weekend, it is not optimal but it was a fun experiment. down below you can see the code in action and an explanation of how it works.
the idea is rather simple. first, we create an image of each character we want to use in our ascii art and cache it. then we go through the original image and for each block of size of the characters we search for the best fit. we do so by first doing some preprocessing of the original image: we convert the image to grayscale and apply a threshold filter. by doing so we get a black and white only contrasted image that we can compare with each character and calculate the difference. we then simply pick the most similar character and do so until the whole image is converted. it is possible to experiment with threshold value to impact contrast and enhance the final result as needed.
a very simple method to accomplish this is to set red, green and blue values to the average of all three:
red = green = blue = (red + green + blue) / 3
if that value is lower than a threshold value, we make it white, otherwise we make it black. finally, we compare that image with each character pixel by pixel and calculate average error. this is demonstrated in the images and snippet below:
int r1 = (charpixel >> 16) & 0xff; int g1 = (charpixel >> 8) & 0xff; int b1 = charpixel & 0xff; int r2 = (sourcepixel >> 16) & 0xff; int g2 = (sourcepixel >> 8) & 0xff; int b2 = sourcepixel & 0xff; int thresholded = (r2 + g2 + b2) / 3 < threshold ? 0 : 255; error = math.sqrt((r1 - thresholded) * (r1 - thresholded) + (g1 - thresholded) * (g1 - thresholded) + (b1 - thresholded) * (b1 - thresholded));
since colors are stored in a single integer, we first extract individual color components and perform calculations i explained. another challenge was to measure character dimensions accurately and to draw them centered. after a lot of experimentation with different methods i finally found this good enough:
rectangle rect = new textlayout(character.tostring((char) i), fm.getfont(), fm.getfontrendercontext()).getoutline(null).getbounds(); g.drawstring(character, 0, (int) (rect.getheight() - rect.getmaxy()));
you can download the complete source code from
here are a few examples with different font sizes and threshold:
Published at DZone with permission of Ivan Korhner, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.