Here I have attached, Simple program about Converting Text to Image using Java Program Example with Random Color. The program was tested and output is shared in same post.

TextToImage.java

package com.javatraineronline;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.imageio.ImageIO;
public class TextToImage {
// Colors can be applied randomly
private Color[] colors = { 
Color.RED, 
Color.BLACK, 
Color.CYAN, 
Color.BLUE,
Color.YELLOW, 
Color.GREEN, 
Color.PINK,
Color.GRAY, 
Color.MAGENTA, 
Color.ORANGE 
};
private int height = 400; // Height of an Image
private int width = 600; // Width of an Image
public boolean convertTextToImage(String strValue) {
if(strValue != null && !"".equals(strValue)) {
// Defining File Object for Output
File file = new File("Output.png");
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB );
Graphics g = image.getGraphics();
g.setFont(g.getFont().deriveFont(10f));
for(int x = 0; x < height; x++) {
for(int y = 0; y < width; y++) {
int randomColor = (int)(Math.random() * 10); // Picking Random Color
g.setColor(colors[randomColor]);
g.drawString(strValue , x*30, y*10); // Adjusting the x and y position
}
}
g.dispose();
try {
return ImageIO.write(image, "png", file); // returning the status of rendering
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("please provide valid string !!!");
}
return false;
}
public static void main(String[] args) {
// Defining the TextToImage Object
TextToImage textToImage = new TextToImage();
Scanner scanner = new Scanner(System.in); // Scanner object to read input from user
System.out.println("Enter your name : ");
String strValue = scanner.nextLine(); 
if(textToImage.convertTextToImage(strValue)) { // Method invocation 'convertTextToImage()'
System.out.println("Image rendered successfully...");
} else {
System.out.println("There is problem to render the image...");
}
}
}

Output

———————-
Enter your name :
Java
Image rendered successfully…

Outcome Image

Converting Text to Image using Java Program

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *