generate Captcha for Servlet - Java 2D Graphics

Java examples for 2D Graphics:Image Captcha

Description

generate Captcha for Servlet

Demo Code

/*/*from w ww .j  a v  a2  s .com*/
 * ProjectName:  rms
 * CaptchaUtils.java
 * cn.wsn.rms.common.util
 *
 * Function TODO 
 *
 *   ver     date            author       email
 * 
 *          2014417    guoqiang     guoqiang@wsn.cn
 *
 * Copyright (c) 2014, WSN All Rights Reserved.
 */
//package com.java2s;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;

public class Main {
    private static String randString = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static String generateCaptcha(OutputStream output)
            throws IOException {
        // 
        int width = 70, height = 30;
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        // 
        Graphics g = image.getGraphics();
        // 
        Random random = new Random();
        // 
        g.setColor(getRandColor(230, 250));
        g.fillRect(0, 0, width, height);
        // 
        g.setFont(new Font("Times New Roman", Font.PLAIN, 20));
        // 155
        g.setColor(getRandColor(1, 245));
        for (int i = 0; i < 2; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }
        // ()
        String randomString = "";
        for (int i = 0; i < 4; i++) {
            String rand = String.valueOf(randString.charAt(random
                    .nextInt(randString.length())));
            randomString += rand;
            // 
            g.setColor(new Color(random.nextInt(101), random.nextInt(111),
                    random.nextInt(121)));
            // 
            g.drawString(rand, 13 * i + 10, 24);
        }
        // 
        g.dispose();
        //   tomcattemp
        try {
            ImageIO.write(image, "JPEG", output);
        } catch (IOException e) {
            throw new IOException(e);
        }
        return randomString;
    }

    private static Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}

Related Tutorials