|
To ASCII art is a technique that uses standard ASCII printable characters to produce visual artistic effect. Historically it has a purpose of its existence, when the printer can not print the image, and the image was embedded in the message also can not be achieved, it is also used in the mail. In this article, I'll show you a very simple code ASCII Art Generator, which is written in Java, and you can configure the font and contrast. Because the generator is I created a couple of hours on the weekend, so it's not perfect, but it is an interesting experiment. Below you can see the realization of the code, and I'll explain how it works.
algorithm
This algorithm is very simple. First, we will use the ASCII art in each of the characters to be converted into an image, and caches it. Then, we traverse the original image, character size for each image block, can find the best match its character. In order to achieve this step, we first do some pre-processing of the original image: we convert the image to grayscale and then allowed to filter through a threshold value, then you get a black and white contrast chart, we can be with each Compare and calculate the difference between the characters. Next, each image block to select the most similar character, always continue until the entire image conversion is complete. In addition, we may also need to be adjusted according to the size of the threshold value to influence the contrast and enhance the final result.
To achieve this, a very simple method is to red, green, and blue values are set to the average of three colors:
Red = green = blue = (red + green + blue) / 3
If this value is below the threshold, we will set it to white, otherwise we will be set to black. Finally, the image of each character to pixel comparison unit and calculate the average error.
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));
Because the color is stored in a single integer, so we first extract a single color component and perform the calculation I explained above. Another challenge is to accurately measure the size of the character, and they plotted to center. After the test a variety of methods, I have found this method is 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 GitHub. |
|
|
|