All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.opslab.util.image.CaptchaUtil Maven / Gradle / Ivy

package com.opslab.util.image;

import com.opslab.util.image.GIF.GifEncoder;

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 CaptchaUtil {
    protected static Font font = new Font("Verdana", Font.ITALIC|Font.BOLD, 28);   // 字体
    /**
     * 产生0--num的随机数,不包括num
     * @param num 数字
     * @return int 随机数字
     */
    public static int num(int num)
    {
        return (new Random()).nextInt(num);
    }
    /**
     * 给定范围获得随机颜色
     * @return Color 随机颜色
     */
    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 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>1) ;
        int w = width/len;
        g2d.setFont(font);
        for(int i=0;i len ? (num *r - s) : num * r;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy