JAVA生成图片验证码API

 效果图:

/**
 * 生成JPG格式的图片验证验证码,存入图片缓冲区BufferedImage
 *
 * @author YangBin
 */
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
class CodeImage {  
    private int height = 35;
    private int width = 70;
    private int num = 4;
    private int fontSize = 15;
    private StringBuilder sb = new StringBuilder();
    private String[] fontName = {"宋体","华文楷体","黑体","微软雅黑"};
    Random rd = new Random();
    
    /** 
     * @return 获取当前二维码图片的长度
     */
    public int getWidth() {
        return width;
    }
    /**
     * @param 设置二维码图片的长度
     */
    public void setWidth(int width) {
        this.width = width;
    }
    /** 
     * @return 获取当前二维码图片的高度
     */
    public int getHeight() {
        return height;
    }
    /**
     * @param heigh 设置二维码图片的高度
     */
    public void setHeight(int height) {
        this.height = height;
    }
    /**
     * @return 返回二维码字符个数
     */
    public int getNum() {
        return num;
    }
    /**
     * @param num 设置二维码的字符个数.
     */
    public void setNum(int num) {
        this.num = num;
    }
    /**
     * @return 当前二维码字体的大小
     */
    public int getFontSize() {
        return fontSize;
    }
    /**
     * @param 获取二维码字体大小
     */
    public void setFontSize(int fontSize) {
        this.fontSize = fontSize;
    }
    /**
     * @return 返回当前生成的二维码的内容
     */
    public String getText(){
        return sb.toString();
    }
    
    /**  
     * @return 返回一个图片缓冲区对象 BufferedImage 包含了绘制完成的图片.
     */
    public BufferedImage getBufferedImage () {
        BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D)bi.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        sb.delete(0, num);
        for(int i=0;i

测试:将生成的图片写入的本地磁盘

public class CreatImage {

	/*
	 * 创建图片;
	 */
	public static void main(String[] args) {
		/*
		 *  Image / ImageIo / BufferedImage / Icon / ImageIcon
		 */
		CodeImage c = new CodeImage();
		
		BufferedImage bi = c.getBufferedImage();
		
		System.out.println(c.getText());
		try {
			
			ImageIO.write(bi, "JPG", new FileOutputStream("E:/abc.jpg"));
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		
	}
}



你可能感兴趣的:(源码)