Articles are constantly updated , You can pay attention to the official account. Program ape Alan Or visit Unread code blog .
this paper Github.com/niumoo/JavaNotes Included , welcome Star.
hello , Hello, everyone , I'm Alan .
already 2022 Years. , The mascot of the recent Beijing Winter Olympics Ice mound A fire , It is said that one pier is hard to find , All kinds of video news are overwhelmed . Programmers should have a programmer's way , Today I'll use Java Draw a Bing dwen dwen made of characters to everyone. , This article records the idea and process of generating character patterns .
Here is a character [email protected]#&8*0.
Characters of ice block pier pattern .
1. Character pattern idea
We all know that a digital picture is a two-dimensional image , It uses a The limited two-dimensional array holds the color information of each pixel , The color information of these pixels is usually used RGB Mode to record . So in essence , Our common image is a two-dimensional array that holds pixel information .
Based on the above picture principle , We can find out , If you want to convert a picture into a character pattern , It only needs Convert the color information of each pixel into a character That's all right. , So we can figure out the steps to convert the picture into character pattern as follows .
- Zoom the picture to the specified size , In order to ensure that the number of characters output will not be too large .
- Traverse the pixels of the picture , Get the color information of each pixel .
- According to the color information of pixels , convert to grayscale ( brightness ) Information .
- Convert the brightness information into corresponding characters .
- Output character pattern , That is, print a two-dimensional character array .
2. Zoom in and out of 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 , Although it will increase the reduction of character images , But it looks very troublesome , Because of so many characters, your screen may not be finished .
therefore , We need to zoom the picture first , Zoom to a certain size and then character it . This is just for convenience , Use it directly Java The self-contained image processing method is used to zoom the image , The following code examples all specify the width for scaling , The height is scaled after being calculated in equal proportion .
Java There are two main ways to adjust the size of the picture. :
- Use
java.awt.Graphics2D
Resize the picture . - Use
Image.getScaledInstance
Resize the picture .
2.1. java.awt.Graphics2D
Graphics2D yes Java The platform provides the ability to render 2D shapes 、 Text 、 Basic class of image , Here's how to use Graphics2D Simple example of image resizing .
/**
* Picture zoom
*
* @param srcImagePath Picture path
* @param targetWidth Target width
* @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;
}
/**
* According to the specified width , Calculate the proportional height
*
* @param targetWidth Target width
* @param srcImage 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;
}
In code BufferedImage.TYPE_INT_RGB
Represents the color model used , All color models can be in Java doc - Image See... In the document .
Resized pictures 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);
Now the original picture is 416 x 500 Image of the Bing dwen dwen to zoom in to 200 x 240 The effect of .
2.2. Image.getScaledInstance
This is a Java Native features are another way to resize pictures , It is easy and convenient to use this method to adjust the size of the picture , The quality of the generated image is also good , The code is simple , however This method is not efficient .
/**
* Picture zoom
*
* @param srcImagePath Picture path
* @param targetWidth Target width
* @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 Same as java.awt.Graphics2D Sample code in
In code Image.SCALE_DEFAULT
Represents the algorithm used for image scaling , stay Java doc - Image All available algorithms can be viewed in the document .
3. RGB Gray calculation
We know that the picture is composed of pixels , Each pixel stores color information , Usually RGB Information , So we want to convert each pixel into characters , That is to put the RGB The grayscale expression of information , Different gray levels give different characters to represent .
For example, we divide the gray scale into 10 Level , Select a character from high to low for each level .
'W', '@', '#', '8', '&', '*', 'o', ':', '.', ' '
So how to calculate the gray scale ? At present, the common calculation method is the average method 、 Weighted mean method 、 Gamma correction method, etc . Here, the mathematical formula similar to the linearity of gamma correction is directly used for calculation , This is also MATLAB、 Pillow and OpenCV Method used .
4. Output character picture
The preliminary preparations have been completed , We have scaled the picture , At the same time, I also know how to put the image on each pixel in the picture RGB The information is converted into gray values , Then we only need to traverse the zoomed image RGB Information , Gray scale conversion , Then select the corresponding character to print .
public static void main(String[] args) throws Exception {
BufferedImage image = resizeImage("/Users/darcy/Downloads/bingdundun.jpeg", 150);
printImage(image);
}
/**
* Character picture printing
*
* @param image
* @throws IOException
*/
public static void printImage(BufferedImage image) throws IOException {
final char[] PIXEL_CHAR_ARRAY = {'W', '@', '#', '8', '&', '*', '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();
// One for calculating RGB The formula of pixel gray
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 Same as the code in part II
Here I choose a picture of an ice pier. , You can see the effect after output .
5. Other character pictures
The following is the effect display of some other pictures to character pictures .
2022 year , Hushengwei character painting .
The attacking giant - Sanli character painting .
As always, , The code in the article is stored in :github.com/niumoo/lab-notes
Reference resources
https://www.kdnuggets.com/2019/12/convert-rgb-image-grayscale.html
https://en.wikipedia.org/wiki/Grayscale
subscribe
You can search through wechat Program ape Alan Or visit Unread code blog read .
this paper Github.com/niumoo/JavaNotes Included , welcome Star.