package com.example.demo.utils;import javax.imageio.ImageIO;import java.awt.*;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.Random;publicclassValidateCodeUtil{protectedstaticchar[] minCh =newchar[]{'0','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','m','n','p','q','r','s','t','u','v','w','x','y','z'};static Random random =newRandom();publicstatic String random(int strLen){returnrandom(minCh, strLen);}publicstatic String random(char[] charArr,int strLen){if(strLen <=0){if(strLen ==0){return"";}else{thrownewIllegalArgumentException();}}else{
Random random =newRandom();
StringBuilder result =newStringBuilder();for(int i =0; i < strLen;++i){int num = random.nextInt(charArr.length);
result.append(charArr[num]);}return result.toString();}}privatestatic Color getRandColor(){
Random random =newRandom();
Color[] color =newColor[10];
color[0]=newColor(32,158,25);
color[1]=newColor(218,42,19);
color[2]=newColor(31,75,208);
color[3]=newColor(0,102,182);
color[4]=newColor(171,0,85);return color[random.nextInt(5)];}publicstatic Font getFont(){
Random random =newRandom();
Font[] font =newFont[]{newFont("Ravie",1,30),newFont("Antique Olive Compact",1,30),newFont("Forte",1,30),newFont("Wide Latin",1,30),newFont("Gill Sans Ultra Bold",1,30)};
font[5]=newFont("Courier New",1,30);return font[random.nextInt(5)];}publicstaticbyte[]render(String randomStr,int width,int height)throws IOException {
ByteArrayOutputStream out =newByteArrayOutputStream();
BufferedImage bi =newBufferedImage(width, height,13);
Graphics2D g =(Graphics2D) bi.getGraphics();
g.setColor(Color.white);
g.fillRect(0,0, width, height);
g.setFont(newFont("Courier New",1,30));
g.setColor(Color.BLACK);
String[] str1 =newString[randomStr.length()];int i;int x;int y;for(i =0; i < str1.length;++i){
str1[i]= randomStr.substring(i, i +1);
y =(i +1)%3;if(y == random.nextInt(7)){
x =30- random.nextInt(7);}else{
x =30+ random.nextInt(7);}
g.setColor(getRandColor());
g.drawString(str1[i],20* i +10, x);}for(i =0; i <100;++i){
x = random.nextInt(width);
y = random.nextInt(height);
Color color =newColor(random.nextInt(255), random.nextInt(255), random.nextInt(255));
g.setColor(color);
g.drawOval(x, y,0,0);}for(i =0; i <15;++i){
x = random.nextInt(width);
y = random.nextInt(height);int x1 = random.nextInt(width);int y1 = random.nextInt(height);
Color color =newColor(random.nextInt(255), random.nextInt(255), random.nextInt(255));
g.setColor(color);
g.drawLine(x, y, x1, y1);}
g.dispose();
ImageIO.write(bi,"png", out);return out.toByteArray();}}