“This is my NTH day of participating in the First Challenge 2022. For details: First Challenge 2022.”

The article continues to be updated, you can follow the public account program ape Alang or visit the unread code blog. This article Github.com/niumoo/Java… Already included, welcome Star.

Hello, everybody. I’m Aaron.

It’s 2022, and bing Dwen Dwen, the mascot of the Beijing Winter Olympic Games, has become so popular that it is said that it is hard to find a new mascot. Programmers should have the way of programmers, today I will use Java to draw a character composed of ice pier pier to everyone, this article records the character pattern generation ideas and process.

Below is an ice block block pattern consisting of characters such as the characters W@#&8*0.

1. Character pattern idea

As we all know, a digital image is a two-dimensional image, which uses a finite two-dimensional array to hold the color information of each pixel. The color information of these pixels is usually recorded in RGB mode. So essentially, our common image is a two-dimensional array of pixels.

Based on the above picture principle, we can find that if we want to convert a picture into a character pattern, we only need to convert the color information of each pixel into a certain character, so we can figure out the steps for converting a picture into a character pattern as follows.

  1. Scale the image to a specified size to ensure that the number of characters in the output is not too large.
  2. Iterate through the pixels of the image to obtain the color information of each pixel.
  3. According to the color information of the pixel, it is converted into gray (brightness) information.
  4. Convert brightness information into corresponding characters.
  5. Output character patterns, that is, print two-dimensional character arrays.

2. Zoom the picture

As mentioned above, since we want to convert the color information of each pixel into a character, if there are too many pixels, the character image will be restored, but it will look very troublesome because your screen may not be able to display all the characters.

Therefore, we need to scale the image to a certain size before characterizing it. Here for convenience, directly use the Java image processing method for image scaling, the following code examples are the specified width for scaling, height and other proportional calculation after scaling.

There are two main ways to resize images in Java:

  1. usejava.awt.Graphics2DResize the image.
  2. useImage.getScaledInstanceResize the image.

2.1. Java. The awt. Graphics2D

Graphics2D is a basic class provided by the Java platform for rendering two-dimensional shapes, text, and images. Here is a simple example of resizing images using Graphics2D.

/** * Image zoom **@paramSrcImagePath Image path *@paramTargetWidth targetWidth *@return
 * @throws IOException
 */
public static BufferedImage resizeImage(String srcImagePath, int targetWidth) throws IOException {
    Image srcImage = ImageIO.read(new File(srcImagePath));
    int targetHeight = getTargetHeight(targetWidth, srcImage);
    BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = resizedImage.createGraphics();
    graphics2D.drawImage(srcImage, 0.0, targetWidth, targetHeight, null);
    graphics2D.dispose();
    return resizedImage;
}

/** * Calculate the proportional height ** according to the specified width@paramTargetWidth targetWidth *@paramSrcImage Image information *@return* /
private static int getTargetHeight(int targetWidth, Image srcImage) {
    int targetHeight = srcImage.getHeight(null);
    if (targetWidth < srcImage.getWidth(null)) {
        targetHeight = Math.round((float)targetHeight / ((float)srcImage.getWidth(null)/(float)targetWidth));
    }
    return targetHeight;
}
Copy the code

The bufferedimage.type_INT_RGB in the code represents the color model used, all of which can be seen in the Java Doc-Image document.

The resized images can be saved in the following ways.

BufferedImage image = resizeImage("/Users/darcy/Downloads/bingdundun.jpeg".200);
File file = new File("/Users/darcy/Downloads/bingdundun_resize.jpg");
ImageIO.write(image, "jpg", file);
Copy the code

Let’s scale the 416 x 500 ice block image to 200 x 240.

2.2. Image. GetScaledInstance

This is another way to resize images using Java native features. It’s easy to resize images, produces good quality images, and has cleaner code, but it’s not very efficient.

/** * Image zoom **@paramSrcImagePath Image path *@paramTargetWidth targetWidth *@return
 * @throws IOException
 */
public static BufferedImage resizeImage2(String srcImagePath, int targetWidth) throws IOException {
    Image srcImage = ImageIO.read(new File(srcImagePath));
    int targetHeight = getTargetHeight(targetWidth, srcImage);
    Image image = srcImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT);
    BufferedImage bufferedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
    bufferedImage.getGraphics().drawImage(image, 0.0.null);
    return bufferedImage;
}
// getTargetHeight is the same as the example code in java.awt.graphics2d

Copy the code

Image.scale_default in the code represents the algorithm used to scale the Image, and you can see all the available algorithms in the Java doc-Image document.

3. RGB grayscale calculation

We know that the picture is composed of pixels, and each pixel stores color information, usually RGB information, so we want to convert each pixel into characters, that is, to express the grayscale of RGB information in pixels, and different grayscales give different characters for representation.

For example, we divide the gray level into 10 levels, and select a character from the highest to the lowest level for identification.

'W', '@', '#', '8', '&', '*', 'o', ':', '.', ' '
Copy the code

So how to do gray scale calculation? At present, the common calculation methods include average method, weighted mean method, gamma correction method and so on. The calculations are made directly using a mathematical formula similar to gamma correction linearity, which is also the method used by MATLAB, Pillow and OpenCV.

4. Output character pictures

Preliminary preparation has been completed, we have scaled the picture, and we also know how to convert the RGB information on each pixel in the picture to gray value, so we just need to traverse the RGB information of the scaled picture, perform gray conversion, and then select the corresponding character for printing.

public static void main(String[] args) throws Exception {
    BufferedImage image = resizeImage("/Users/darcy/Downloads/bingdundun.jpeg".150);
    printImage(image);
}

/** * character picture print **@param image
 * @throws IOException
 */
public static void printImage(BufferedImage image) throws IOException {
    final char[] PIXEL_CHAR_ARRAY = {'W'.The '@'.The '#'.'8'.'&'.The '*'.'o'.':'.'. '.' '};
    int width = image.getWidth();
    int height = image.getHeight();
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            int rgb = image.getRGB(j, i);
            Color color = new Color(rgb);
            int red = color.getRed();
            int green = color.getGreen();
            int blue = color.getBlue();
            // a formula for calculating the grayscale of RGB pixels
            Double grayscale = 0.2126 * red + 0.7152 * green + 0.0722 * blue;
            double index = grayscale / (Math.ceil(255 / PIXEL_CHAR_ARRAY.length) + 0.5);
            System.out.print(PIXEL_CHAR_ARRAY[(int)(Math.floor(index))]); } System.out.println(); }}// resizeImage is the same as part 2 of the code

Copy the code

Here I choose a picture of Bing Dwen dwen, you can see the output effect.

5. Other character pictures

Here are some other picture to character diagrams.

In 2022, tiger Tiger character painting.

Attack the giant character – three hats character painting.

As always, the code for this article is at: github.com/niumoo/lab-…

reference

www.kdnuggets.com/2019/12/con…

En.wikipedia.org/wiki/Graysc…

To subscribe to

You can search App Alang on wechat or visit the unread code blog to read. This article Github.com/niumoo/Java… Already included, welcome Star.