Captcha is use for human validation and you can make an costume captcha image in java-
Example:
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Captcha
extends HttpServlet
{
private static final long serialVersionUID = -4687606895768367L;
private int height = 0;
private int width = 0;
public static final String CAPTCHA_KEY = "captcha_key_name";
private String severIP = null;
public void init( ServletConfig config )
throws ServletException
{
super.init( config );
height = Integer.parseInt( getServletConfig().getInitParameter( "height" ) );
width = Integer.parseInt( getServletConfig().getInitParameter( "width" ) );
}
protected void doGet( HttpServletRequest req, HttpServletResponse response )
throws IOException, ServletException
{
//Expire response
response.setHeader( "Cache-Control", "no-cache" );
response.setDateHeader( "Expires", 0 );
response.setHeader( "Pragma", "no-cache" );
response.setDateHeader( "Max-Age", 0 );
BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
Graphics2D graphics2D = image.createGraphics();
Random r = new Random();
int ch = 0;
int x = r.nextInt(32) ;
int y = r.nextInt(32);
ch = x+y;
String drawCh = x + " + " + y ;
Color c = new Color( 228, 0 , 0 );
Color c1 = new Color(237, 239, 241);
GradientPaint gp = new GradientPaint( 30, 30, c, 15, 25, Color.GRAY, true );
//set background color
graphics2D.setColor( c1 );
//fill background color
graphics2D.fillRect(0, 0, width, height);
graphics2D.setPaint( gp );
Font font = new Font( "opensans_regular", Font.BOLD,13 );
graphics2D.setFont( font );
graphics2D.drawString( drawCh,5,21);
graphics2D.dispose();
HttpSession session = req.getSession( true );
session.setAttribute( CAPTCHA_KEY, ch );
OutputStream outputStream = response.getOutputStream();
ImageIO.write( image, "jpeg", outputStream );
outputStream.close();
}
}
Comments
Post a Comment