This is a code snippet which can be used to generate random captcha images. This implementation is a change password scenario where in the user has to enter the captcha in order to validate the change of password is being done by a person. Here is a Java Program to
import java.io.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.*;
import java.util.Random;
import javax.imageio.ImageIO;
/**
* Servlet implementation class CaptchaServlet
*/
public class Captcha {
public Captcha() {
super();
// TODO Auto-generated constructor stub
}
public void generateCaptcha()
throws IOException
{
int width = 150;
int height = 50;
Random r=new Random();
String token=Long.toString(Math.abs(r.nextLong()),36);
String captcha=token.substring(0,6);
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedImage.createGraphics();
Font font = new Font("Georgia", Font.BOLD, 18);
g2d.setFont(font);
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHints(rh);
GradientPaint gp = new GradientPaint(0, 0,
Color.red, 0, height/2, Color.black, true);
g2d.setPaint(gp);
g2d.fillRect(0, 0, width, height);
g2d.setColor(new Color(255, 153, 0));
int x = 0;
int y = 0;
char[] arr=captcha.toCharArray();
for (int i=0; i<6; i++) {
x += 10 + (Math.abs(r.nextInt()) % 15);
y = 20 + Math.abs(r.nextInt()) % 20;
g2d.drawChars(arr, i, 1, x, y);
}
g2d.dispose();
//bufferedImage is the captcha image
}