Java圖片驗(yàn)證碼

采用驗(yàn)證碼很重要的原因就是為了防止系統(tǒng)被攻擊蜻直,比如機(jī)器重復(fù)注冊盯质,短信重復(fù)發(fā)送;
下面介紹常用的兩種驗(yàn)證碼:數(shù)字驗(yàn)證碼和算法驗(yàn)證碼

基本原理分為兩步:
1)驗(yàn)證碼生成:先生成隨機(jī)數(shù)概而,把結(jié)果存在session中呼巷,然后生成圖片,并把圖片返回前端赎瑰,當(dāng)然王悍,也可以存儲到redis中
2)驗(yàn)證碼驗(yàn)證:前端輸入驗(yàn)證碼后,后端使用session中存的驗(yàn)證碼和前端傳參驗(yàn)證碼做校驗(yàn)
注:如果是短信發(fā)送需要驗(yàn)證碼的話餐曼,需要注意一點(diǎn)压储,在發(fā)送短信時,參數(shù)除了要有手機(jī)號以外晋辆,還需要有驗(yàn)證碼渠脉,后端接收到以后宇整,還需要驗(yàn)證一次瓶佳,驗(yàn)證成功以后,要把session中的驗(yàn)證碼刪除鳞青,防止霸饲,惡意攻擊

1为朋、隨機(jī)數(shù)驗(yàn)證碼

public void getImageCode1(HttpServletRequest request, HttpServletResponse response){
         try {
             // 設(shè)置響應(yīng)的類型格式為圖片格式
             response.setContentType("image/jpeg");
             // 禁止圖像緩存。
             response.setHeader("Pragma","no-cache");
             response.setHeader("Cache-Control","no-cache");
             response.setDateHeader("Expires",0);

             // 生成隨機(jī)字串
             String verifyCode = VerifyCodeUtils.generateVerifyCode(4);

             HttpSession session = request.getSession(true);
             // 刪除以前的
             session.removeAttribute("verifyCode");
             // 存入會話session
             session.setAttribute("verifyCode", verifyCode.toLowerCase());
             request.getSession().setAttribute("codeTime",new Date().getTime());
             // 生成圖片
             int w = 150, h = 30;
             VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
         } catch (IOException e) {
             logger.error("生成圖片驗(yàn)證碼失敗厚脉,{}",e);
         }

     }

2习寸、算法驗(yàn)證碼

public void test(HttpServletRequest request, HttpServletResponse response){
        try {
            // 設(shè)置響應(yīng)的類型格式為圖片格式
            response.setContentType("image/jpeg");
            // 禁止圖像緩存。
            response.setHeader("Pragma","no-cache");
            response.setHeader("Cache-Control","no-cache");
            response.setDateHeader("Expires",0);
            // 生成圖片
            int width = 140, height = 40;

            String baseStr = generateCheckCode(request);
            logger.info("生成驗(yàn)證碼{}",baseStr);
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            OutputStream os = response.getOutputStream();
            Graphics g = image.getGraphics();

            Random random = new Random();

            g.setColor(getRandColor(random, 200, 250));
            g.fillRect(0, 0, width, height);

            String[] fontTypes = { "\u5b8b\u4f53", "\u65b0\u5b8b\u4f53", "\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66" };
            int fontTypesLength = fontTypes.length;

            g.setColor(getRandColor(random, 160, 200));
            g.setFont(new Font("Times New Roman", Font.PLAIN, 14 + random.nextInt(6)));

            for (int i = 0; i < 255; 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 [] baseChar = baseStr.split(" ");
            for (int i = 0; i < baseChar.length; i++) {
                g.setColor(getRandColor(random, 30, 150));
                g.setFont(new Font(fontTypes[random.nextInt(fontTypesLength)], Font.BOLD, 22 + random.nextInt(6)));
                g.drawString(baseChar[i], 24 * i + 10, 24);
            }

            g.dispose();

            //發(fā)送圖片
            ImageIO.write(image, "JPEG", os);
            os.flush();
            os.close();
            os = null;
            response.flushBuffer();

        } catch (Exception e) {
            logger.error("獲取驗(yàn)證碼出錯{}",e);

        }

 private static Color getRandColor(Random random, int fc, int bc){
        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);
    }

private static String generateCheckCode(HttpServletRequest request) {
        Random random = new Random();
        int intTemp;
        int intFirst = random.nextInt(100);
        int intSec = random.nextInt(100);
        String checkCode = "";
        int result = 0;
        switch (random.nextInt(6)) {
            case 0:
                if (intFirst < intSec) {
                    intTemp = intFirst;
                    intFirst = intSec;
                    intSec = intTemp;
                }
                checkCode = intFirst + " - " + intSec + " = ?";
                result = intFirst-intSec;
                break;
            case 1:
                if (intFirst < intSec) {
                    intTemp = intFirst;
                    intFirst = intSec;
                    intSec = intTemp;
                }
                checkCode = intFirst + " - ? = "+(intFirst-intSec);
                result = intSec;
                break;
            case 2:
                if (intFirst < intSec) {
                    intTemp = intFirst;
                    intFirst = intSec;
                    intSec = intTemp;
                }
                checkCode = "? - "+intSec+" = "+(intFirst-intSec);
                result = intFirst;
                break;
            case 3:
                checkCode = intFirst + " + " + intSec + " = ?";
                result = intFirst + intSec;
                break;
            case 4:
                checkCode = intFirst + " + ? ="+(intFirst+intSec);
                result = intSec;
                break;
            case 5:
                checkCode = "? + " + intSec + " ="+(intFirst+intSec);
                result = intFirst;
                break;
        }
        request.getSession().setAttribute("VERIFY_CODE", result);
        request.getSession().setAttribute("codeTime",new Date().getTime());
        return checkCode;
    }

校驗(yàn)

public Result verifyImageCode2(HttpServletRequest request, HttpSession session, String checkCode){
        Result result = new Result();

        //獲得session中驗(yàn)證碼
        Object verifyCode = session.getAttribute("VERIFY_CODE");
        if(verifyCode == null){
            result.setCode(Result.STATUS_ERROR);
            result.setMsg("驗(yàn)證碼已過期傻工,請重新獲取驗(yàn)證碼霞溪!");
            return  result;
        }
        logger.info("校驗(yàn)驗(yàn)證碼{}={}",checkCode,verifyCode);
        // 驗(yàn)證碼有效時長為1分鐘
        Long codeTime = Long.valueOf(session.getAttribute("codeTime") + "");
        Date now = new Date();
        if ((now.getTime() - codeTime) / 1000 / 60 > 1){
            result.setCode(Result.STATUS_ERROR);
            result.setMsg("驗(yàn)證碼已失效,請重新輸入中捆!");
            return  result;
        }


        if(StringUtil.isEmpty(checkCode) || StringUtil.isEmpty(verifyCode.toString()) ||
                !verifyCode.toString().equalsIgnoreCase(checkCode)){
            result.setCode(Result.STATUS_ERROR);
            result.setMsg("驗(yàn)證碼錯誤鸯匹,請重新輸入!");
            return  result;
        }

        result.setCode(Result.STATUS_OK);
        result.setMsg("驗(yàn)證通過泄伪!");
        return  result;
    }

3殴蓬、滑動圖片驗(yàn)證碼

public Result getImageCode(HttpSession session, HttpServletResponse response,String userId,String phone) {
        Result result = new Result();
        logger.info("獲取滑動圖片,userId={},phone={}",userId,phone);
        //生成圖片驗(yàn)證碼
        int L = new Random().nextInt(180)+56;
        int W = new Random().nextInt(100);
        Map<String, Object> resultMap = new HashMap<>();
        String url = "https://picsum.photos/300/150/?image=" + new Random().nextInt(100);
        int type = 1;
        this.createImage(url, L, W, resultMap);

        int resultImageLength = L*280/300;
        int resultImageWidth= W*200/150;
        resultMap.put("w",resultImageWidth);

        //存儲驗(yàn)證碼
        //把移動距離存儲起來
        String sessionId = session.getId();
        String key = StringUtil.join("_",userId,sessionId,phone,"YOUZAN");
        RedisKit.setCache(key,resultImageLength,60L);

        result.OK(resultMap);
        return result;
    }

public static Map<String,Object> createImage(String urlStr, int L, Integer W, Map<String,Object> resultMap){
        try {
             int targetLength=56;//小圖長
             int targetWidth=40;//小圖寬
            //new 一個URL對象
            URL url = new URL(urlStr);
            //打開鏈接
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //設(shè)置請求方式為"GET"
            conn.setRequestMethod("GET");
            //超時響應(yīng)時間為5秒
            conn.setConnectTimeout(5 * 1000);
            //通過輸入流獲取圖片數(shù)據(jù)
            if(conn.getResponseCode()==200) {
                InputStream inStream = conn.getInputStream();

                BufferedImage bufferedImage = ImageIO.read(new BufferedInputStream(inStream));
                BufferedImage target= new BufferedImage(targetLength, targetWidth, BufferedImage.TYPE_4BYTE_ABGR);

                cutByTemplate(bufferedImage,target,getBlockData(targetLength,targetWidth),targetLength, targetWidth,L,W);

                //OutputStream os = response.getOutputStream();

                //原始 大圖
//                if(type == 1) {
//                    //ImageIO.write(bufferedImage, "jpg", os);
//                }

                BufferedImage srcImage = simpleBlur(bufferedImage, null);
                //模糊處理 大圖
//                if(type ==2) {
//                    //ImageIO.write(srcImage, "jpg", os);
//                }
//
//                //壓縮  大圖
//                if(type == 3) {
//                    //fromBufferedImage2(srcImage, "jpg", response);
//                }
                byte[] bigImages = fromBufferedImage2(srcImage, "jpg");
                //小圖
//                if(type == 4) {
//                    //ImageIO.write(target, "jpg", os);
//                }
                resultMap.put("b",bigImages);//大圖
                //resultMap.put("b", getImageBytes(srcImage));//大圖
                resultMap.put("s", getImageBytes(target));//小圖
            }else {
                createImage(urlStr, L, W, resultMap);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }finally{
            return resultMap;
        }
    }

private static void cutByTemplate(BufferedImage oriImage,BufferedImage targetImage, int[][] templateImage,int targetLength,int targetWidth, int x,int y) {
        for (int i = 0; i < targetLength; i++) {
            for (int j = 0; j < targetWidth; j++) {
                int rgb = templateImage[i][j];
                // 原圖中對應(yīng)位置變色處理
                int rgb_ori = oriImage.getRGB(x + i, y + j);

                if (rgb == 1) {
                    //摳圖上復(fù)制對應(yīng)顏色值
                    targetImage.setRGB(i, j, rgb_ori);
                    String hexStr = randomHexString(6);
                    //原圖對應(yīng)位置顏色變化

                    //int r = (0xff & rgb_ori);
                    //int g = (0xff & (rgb_ori >> 8));
                    //int b = (0xff & (rgb_ori >> 16));
                    //rgb_ori = r + (g << 8) + (b << 16) + (200 << 22);
                    //oriImage.setRGB(x + i, y + j, rgb_ori );
                    oriImage.setRGB(x + i, y + j, rgb_ori + Integer.parseInt(hexStr, 16));
                    //oriImage.setRGB(x + i, y + j,rgb_ori & 0x363636);
                } else{
                    //這里把背景設(shè)為透明
                    targetImage.setRGB(i, j, rgb_ori & 0x00ffffff);
                    //oriImage.setRGB(x + i, y + j, rgb_ori & 0x363636 );
                }
            }
        }
    }

private static int[][] getBlockData( int targetLength, int targetWidth) {

         int circleR=6;//半徑
         int r1=3;//距離點(diǎn)
        int[][] data = new int[targetLength][targetWidth];
        double x2 = targetLength - circleR;

        //隨機(jī)生成圓的位置
        double h1 = circleR + Math.random() * (targetWidth - 3 * circleR - r1);
        double po = circleR * circleR;

        double xbegin = targetLength - circleR - r1;
        double ybegin = targetWidth - circleR - r1;

        for (int i = 0; i < targetLength; i++) {
            for (int j = 0; j < targetWidth; j++) {
                double d3 = Math.pow(i - x2, 2) + Math.pow(j - h1, 2);
                double d2 = Math.pow(j - 2, 2) + Math.pow(i - h1, 2);
                if ((j <= ybegin && d2 <= po) || (i >= xbegin && d3 >= po)) {
                    data[i][j] = 0;
                } else {
                    data[i][j] = 1;
                }

            }
        }
        return data;
    }

public static String randomHexString(int len)  {
        try {
            StringBuffer result = new StringBuffer();
            for(int i=0;i<len;i++) {
                result.append(Integer.toHexString(new Random().nextInt(5)+1));
            }
            return result.toString().toUpperCase();

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();

        }
        return null;
    }

public static byte[] fromBufferedImage2(BufferedImage img,String imageType) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bos.reset();
        // 得到指定Format圖片的writer
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(imageType);
        ImageWriter writer = (ImageWriter) iter.next();

        // 得到指定writer的輸出參數(shù)設(shè)置(ImageWriteParam )
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // 設(shè)置可否壓縮
        iwp.setCompressionQuality(1f); // 設(shè)置壓縮質(zhì)量參數(shù)
        iwp.setProgressiveMode(ImageWriteParam.MODE_DISABLED);

        ColorModel colorModel = ColorModel.getRGBdefault();
        // 指定壓縮時使用的色彩模式
        iwp.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel,
                colorModel.createCompatibleSampleModel(16, 16)));

        writer.setOutput(ImageIO.createImageOutputStream(bos));
        IIOImage iImage = new IIOImage(img, null, null);
        writer.write(null, iImage, iwp);

        byte[] d = bos.toByteArray();

        //ByteArrayInputStream in = new ByteArrayInputStream(d);    //將b作為輸入流蟋滴;

        //BufferedImage image = ImageIO.read(in);

        //OutputStream os = response.getOutputStream();
        //大圖
        //ImageIO.write(image, "jpg", os);

        return d;
    }

public static BufferedImage simpleBlur(BufferedImage src,BufferedImage dest) {
        BufferedImageOp op = getGaussianBlurFilter(2,false);
        dest = op.filter(src, dest);
        return dest;
    }

public static ConvolveOp getGaussianBlurFilter(int radius,
                                                   boolean horizontal) {
        if (radius < 1) {
            throw new IllegalArgumentException("Radius must be >= 1");
        }

        int size = radius * 2 + 1;
        float[] data = new float[size];

        float sigma = radius / 3.0f;
        float twoSigmaSquare = 2.0f * sigma * sigma;
        float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI);
        float total = 0.0f;

        for (int i = -radius; i <= radius; i++) {
            float distance = i * i;
            int index = i + radius;
            data[index] = (float) Math.exp(-distance / twoSigmaSquare) / sigmaRoot;
            total += data[index];
        }

        for (int i = 0; i < data.length; i++) {
            data[i] /= total;
        }

        Kernel kernel = null;
        if (horizontal) {
            kernel = new Kernel(size, 1, data);
        } else {
            kernel = new Kernel(1, size, data);
        }
        return new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
    }

public static byte[] getImageBytes(BufferedImage image) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image,"png",out);
        byte[] b = out.toByteArray();//轉(zhuǎn)成byte數(shù)組
       // BASE64Encoder encoder = new BASE64Encoder();
        return b;//生成base64編碼
    }

校驗(yàn)

//校驗(yàn) 滑動圖片 驗(yàn)證碼, 校驗(yàn)成功以后  發(fā)送短信
    @RequestMapping(value = "/verifyImageCode.json", method = RequestMethod.POST)
    @ResponseBody
    public Result verifyImageCode(HttpSession session,String userId,Long orgId,String phone,String index){
        Result result = new Result();
        try {
            //校驗(yàn)驗(yàn)證碼
            String sessionId = session.getId();

            logger.info("校驗(yàn)滑動圖片染厅,sessionId={},userId={},phone={},index={}",sessionId,userId,phone,index);

            String key = StringUtil.join("_",userId,sessionId,phone,"YOUZAN");
            Integer value = RedisKit.getCache(key);

            if(null == value){
                result.setCode(Result.STATUS_ERROR);
                result.setMsg("驗(yàn)證失敗=蚝Pち浮!");
                return  result;
            }

            //刪除key
            RedisKit.deleteCache(key);
            //誤差范圍為+-2
            //不在誤差范圍內(nèi)
            if(Math.abs(Double.valueOf(value)-Double.valueOf(index))>2){
                result.setCode(Result.STATUS_ERROR);
                result.setMsg("驗(yàn)證失敹唷D蜃!蕉堰!");
                return  result;
            }

            result.OK("驗(yàn)證通過凌净,短信驗(yàn)證碼已發(fā)送");
            // 校驗(yàn)成功以后,發(fā)送短信
            smsService.sendSmsCode(orgId,"YOUZAN",phone);

        } catch (Exception e) {
            logger.error("發(fā)送短信驗(yàn)證碼失敗屋讶,{}",e);
        }
        return  result;
    }

4冰寻、工具類

package com.vendor.util.msg;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
import javax.imageio.ImageIO;


/**
 * Created by zhangkai on 2019/2/16.
 */
public class VerifyCodeUtils {
    // 使用到Algerian字體,系統(tǒng)里沒有的話需要安裝字體皿渗,字體只顯示大寫斩芭,去掉了1,0,i,o幾個容易混淆的字符
    public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static Random random = new Random();

    /**
     * 使用系統(tǒng)默認(rèn)字符源生成驗(yàn)證碼
     *
     * @param verifySize
     *            驗(yàn)證碼長度
     * @return
     */
    public static String generateVerifyCode(int verifySize) {
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }

    /**
     * 使用指定源生成驗(yàn)證碼
     *
     * @param verifySize
     *            驗(yàn)證碼長度
     * @param sources
     *            驗(yàn)證碼字符源
     * @return
     */
    public static String generateVerifyCode(int verifySize, String sources) {
        if (sources == null || sources.length() == 0) {
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for (int i = 0; i < verifySize; i++) {
            verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
        }
        return verifyCode.toString();
    }

    /**
     * 生成隨機(jī)驗(yàn)證碼文件,并返回驗(yàn)證碼值
     *
     * @param w
     * @param h
     * @param outputFile
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, outputFile, verifyCode);
        return verifyCode;
    }

    /**
     * 輸出隨機(jī)驗(yàn)證碼圖片流,并返回驗(yàn)證碼值
     *
     * @param w
     * @param h
     * @param os
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, os, verifyCode);
        return verifyCode;
    }

    /**
     * 生成指定驗(yàn)證碼圖像文件
     *
     * @param w
     * @param h
     * @param outputFile
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
        if (outputFile == null) {
            return;
        }
        File dir = outputFile.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            outputFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(outputFile);
            outputImage(w, h, fos, code);
            fos.close();
        } catch (IOException e) {
            throw e;
        }
    }

    /**
     * 輸出指定驗(yàn)證碼圖片流
     *
     * @param w
     * @param h
     * @param os
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Random rand = new Random();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Color[] colors = new Color[5];
        Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.YELLOW };
        float[] fractions = new float[colors.length];
        for (int i = 0; i < colors.length; i++) {
            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
            fractions[i] = rand.nextFloat();
        }
        Arrays.sort(fractions);

        g2.setColor(Color.GRAY);// 設(shè)置邊框色
        g2.fillRect(0, 0, w, h);

        Color c = getRandColor(200, 250);
        g2.setColor(c);// 設(shè)置背景色
        g2.fillRect(0, 2, w, h - 4);

        // 繪制干擾線
        Random random = new Random();
        g2.setColor(getRandColor(160, 200));// 設(shè)置線條的顏色
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(w - 1);
            int y = random.nextInt(h - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }

        // 添加噪點(diǎn)
        float yawpRate = 0.05f;// 噪聲率
        int area = (int) (yawpRate * w * h);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            int rgb = getRandomIntColor();
            image.setRGB(x, y, rgb);
        }

        shear(g2, w, h, c);// 使圖片扭曲

        g2.setColor(getRandColor(100, 160));
        int fontSize = h - 4;
        Font font = new Font("Algerian", Font.ITALIC, fontSize);
        g2.setFont(font);
        char[] chars = code.toCharArray();
        for (int i = 0; i < verifySize; i++) {
            AffineTransform affine = new AffineTransform();
            affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
            g2.setTransform(affine);
            g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
        }

        g2.dispose();
        ImageIO.write(image, "jpg", os);
    }

    private static Color getRandColor(int fc, int bc) {
        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);
    }

    private static int getRandomIntColor() {
        int[] rgb = getRandomRgb();
        int color = 0;
        for (int c : rgb) {
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private static int[] getRandomRgb() {
        int[] rgb = new int[3];
        for (int i = 0; i < 3; i++) {
            rgb[i] = random.nextInt(255);
        }
        return rgb;
    }

    private static void shear(Graphics g, int w1, int h1, Color color) {
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    private static void shearX(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(2);

        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            if (borderGap) {
                g.setColor(color);
                g.drawLine((int) d, i, 0, i);
                g.drawLine((int) d + w1, i, w1, i);
            }
        }

    }

    private static void shearY(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(40) + 10; // 50;

        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }

        }

    }

    /*
     * public static void main(String[] args) throws IOException { File dir =
     * new File("F:/verifies"); int w = 200, h = 80; for (int i = 0; i < 50;
     * i++) { String verifyCode = generateVerifyCode(4); File file = new
     * File(dir, verifyCode + ".jpg"); outputImage(w, h, file, verifyCode); } }
     */
}


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市乐疆,隨后出現(xiàn)的幾起案子划乖,更是在濱河造成了極大的恐慌,老刑警劉巖挤土,帶你破解...
    沈念sama閱讀 207,248評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件琴庵,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)迷殿,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,681評論 2 381
  • 文/潘曉璐 我一進(jìn)店門儿礼,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人庆寺,你說我怎么就攤上這事蚊夫。” “怎么了懦尝?”我有些...
    開封第一講書人閱讀 153,443評論 0 344
  • 文/不壞的土叔 我叫張陵知纷,是天一觀的道長。 經(jīng)常有香客問我陵霉,道長屈扎,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,475評論 1 279
  • 正文 為了忘掉前任撩匕,我火速辦了婚禮鹰晨,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘止毕。我一直安慰自己模蜡,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,458評論 5 374
  • 文/花漫 我一把揭開白布扁凛。 她就那樣靜靜地躺著忍疾,像睡著了一般。 火紅的嫁衣襯著肌膚如雪谨朝。 梳的紋絲不亂的頭發(fā)上卤妒,一...
    開封第一講書人閱讀 49,185評論 1 284
  • 那天,我揣著相機(jī)與錄音字币,去河邊找鬼则披。 笑死,一個胖子當(dāng)著我的面吹牛洗出,可吹牛的內(nèi)容都是我干的士复。 我是一名探鬼主播,決...
    沈念sama閱讀 38,451評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼翩活,長吁一口氣:“原來是場噩夢啊……” “哼阱洪!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起菠镇,我...
    開封第一講書人閱讀 37,112評論 0 261
  • 序言:老撾萬榮一對情侶失蹤冗荸,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后利耍,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蚌本,經(jīng)...
    沈念sama閱讀 43,609評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡盔粹,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,083評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了魂毁。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片玻佩。...
    茶點(diǎn)故事閱讀 38,163評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡出嘹,死狀恐怖席楚,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情税稼,我是刑警寧澤烦秩,帶...
    沈念sama閱讀 33,803評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站郎仆,受9級特大地震影響只祠,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜扰肌,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,357評論 3 307
  • 文/蒙蒙 一抛寝、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧曙旭,春花似錦盗舰、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,357評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至剂习,卻和暖如春蛮位,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背鳞绕。 一陣腳步聲響...
    開封第一講書人閱讀 31,590評論 1 261
  • 我被黑心中介騙來泰國打工失仁, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人们何。 一個月前我還...
    沈念sama閱讀 45,636評論 2 355
  • 正文 我出身青樓陶因,卻偏偏與公主長得像,于是被迫代替她去往敵國和親垂蜗。 傳聞我的和親對象是個殘疾皇子楷扬,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,925評論 2 344

推薦閱讀更多精彩內(nèi)容