png Captcha - Java 2D Graphics

Java examples for 2D Graphics:Image Captcha

Description

png Captcha

Demo Code


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

public class Main{
    public static void main(String[] argv) throws Exception{
        String randomStr = "java2s.com";
        int width = 2;
        int height = 2;
        String file = "java2s.com";
        System.out.println(pngCaptcha(randomStr,width,height,file));
    }/*  w  w w .  ja v  a  2  s .c om*/
    protected static Font font = new Font("Verdana", Font.ITALIC
            | Font.BOLD, 28);
    public static boolean pngCaptcha(String randomStr, int width,
            int height, String file) {
        char[] strs = randomStr.toCharArray();
        try (OutputStream out = new FileOutputStream(file)) {
            BufferedImage bi = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = (Graphics2D) bi.getGraphics();
            AlphaComposite ac3;
            Color color;
            int len = strs.length;
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, width, height);
            for (int i = 0; i < 15; i++) {
                color = color(150, 250);
                g.setColor(color);
                g.drawOval(num(width), num(height), 5 + num(10),
                        5 + num(10));
            }
            g.setFont(font);
            int h = height - ((height - font.getSize()) >> 1), w = width
                    / len, size = w - font.getSize() + 1;
            for (int i = 0; i < len; i++) {
                // 
                ac3 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                        0.7f);
                g.setComposite(ac3);

                color = new Color(20 + num(110), 30 + num(110),
                        30 + num(110));
                g.setColor(color);
                g.drawString(strs[i] + "", (width - (len - i) * w) + size,
                        h - 4);
            }
            ImageIO.write(bi, "png", out);
            out.flush();
            return true;
        } catch (IOException e) {
            return false;
        }
    }
    
    protected static Color color(int fc, int bc) {
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + num(bc - fc);
        int g = fc + num(bc - fc);
        int b = fc + num(bc - fc);
        return new Color(r, g, b);
    }
    
    public static int num(int num) {
        return (new Random()).nextInt(num);
    }
}

Related Tutorials