This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
🧧 Review raffle
-
Raffle gift: 100 pieces, including badges, slippers, mugs, canvas bags, etc., will be distributed at random
-
Drawing time: Within 3 working days after the end of project Diggnation, all articles that meet the rules will be officially posted in the comments section
-
Lucky draw: Nuggets official random draw + manual verification
-
Comment content: comments, suggestions and discussions related to the content of the article. General comments such as “treading on” and “learning” will not win the prize
🎀 preface
Recently had a friend, take the packing of your resume to a company to dry goods, although not a giant, but also led to the oneself life the first demand, although said that the demand I looks not very hard, but for the kind of man who taught himself turned my friends still have certain difficulty, let’s take a look at what needs to this demand, it is simple: Use Java code to generate random images with light backgrounds based on text, and the font should also be changeable.
I drop darling, this demand to a just come in the company directly to 👨 whole won’t. So let’s see how I made this requirement. It’s really just a few key words: generate images from text, change font, light background.
💎 code
Without further ado, let’s get right to it. First we will create a name.txt file on disk D, we will read the text here to generate pictures later.
Read the name in the file
Next we’ll write a method to read the name in the file. We use an InputStreamReader to read it and return a List.
/ * * *@Description: Returns * for reading the text line by line from the file and placing it in the List@Param: [filename] indicates the filename *@return java.util.List<java.lang.String>
*/
public static List<String> readFileByLine(String filename) throws IOException, FileNotFoundException {
List<String> stringList=new ArrayList<String>();
File file=new File(filename);
InputStreamReader isr=new InputStreamReader(new FileInputStream(file),"UTF-8");
BufferedReader reader=new BufferedReader(isr);
String tmp;
while((tmp=reader.readLine())! =null){
stringList.add(tmp);
}
reader.close();
return stringList;
}
Copy the code
Generate images
/ * * *@Description: Method for generating images *@Param: [string] Generates the text content of the image *@return void
*/
public static void generateImg(String string) throws IOException{
// Set the image width and height
int width=400;
int height=400;
// Set the path of the image
String filename="D:/"+string+".jpg";
System.out.println(filename);
File file=new File(filename);
// There is no need to introduce external fonts
Font font=new Font("Black",Font.BOLD,60);
// Introduce external fonts
//Font Font = getSelfDefinedFont("E:\PangMenZhengDaoBiaoTiTi\ think source.ttf");
BufferedImage bi =new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2=(Graphics2D) bi.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setBackground(getRandomColor());
g2.clearRect(0.0, width, height);
g2.setFont(font);
FontMetrics fm = g2.getFontMetrics(font);
int textWidth = fm.stringWidth(string);
g2.setPaint(new Color(0.0.128));
// Center the image horizontally
int widthX = (width - textWidth) / 2;
// Set the height of y, so far there is no research method in the middle
g2.drawString(string, widthX , 220);
ImageIO.write(bi,"jpg", file);
}
Copy the code
Here are some things to note:
- I have two ways to do this. The first way is to use the built-in fonts instead of the external ones.
- We can download fonts ourselves and import them through a unique path. Font file format must be TTF, other I tried is not effective, and must use no copyright or free commercial font.
- I did horizontal center here, but vertical center has not been studied out, can only be adjusted slowly according to the actual effect.
Create a light background
In fact, to generate a light background I can think of using RGB in a certain range of random generation to generate a light background.
/ * * *@Description: Set a random light color *@Param* : []@return java.awt.Color
*/
private static Color getRandomColor(a) {
Random random=new Random();
// I set the image to return light color, excluding dark color
return new Color(random.nextInt(255) % (255-230+1) + 200,random.nextInt(255) % (255-230+1) + 200,random.nextInt(255) % (255-230+1) + 200);
}
Copy the code
Write the main method
Now that the body code is done, let’s test it by writing the main method.
String fileName="D:/name.txt";
List<String> nameList = readFileByLine(fileName);
for (int i = 0; i < nameList.size(); i++) {
generateImg(nameList.get(i));
}
Copy the code
🎉 test
Ok! Hee hee