-
Notifications
You must be signed in to change notification settings - Fork 404
/
Converting-Text-To-Image.java
45 lines (32 loc) · 1.36 KB
/
Converting-Text-To-Image.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class TextToImageDemo{
public static void main(String[] args) throws IOException{
//create String object to be converted to image
String sampleText = "SAMPLE TEXT";
//Image file name
String fileName = "Image";
//create a File Object
File newFile = new File("./" + fileName + ".jpeg");
//create the font you wish to use
Font font = new Font("Tahoma", Font.PLAIN, 11);
//create the FontRenderContext object which helps us to measure the text
FontRenderContext frc = new FontRenderContext(null, true, true);
//get the height and width of the text
Rectangle2D bounds = font.getStringBounds(sampleText, frc);
int w = (int) bounds.getWidth();
int h = (int) bounds.getHeight();
//create a BufferedImage object
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
//calling createGraphics() to get the Graphics2D
Graphics2D g = image.createGraphics();
//set color and other parameters
g.setColor(Color.WHITE);
g.fillRect(0, 0, w, h);
g.setColor(Color.BLACK);
g.setFont(font);
g.drawString(sampleText, (float) bounds.getX(), (float) -bounds.getY());
//releasing resources
g.dispose();
//creating the file
ImageIO.write(image, "jpeg", fileName);
}
}