验证码 Demo

         //设置响应头
response.setCharacterEncoding("image/jpeg");
int width=160;
int height=40;
BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, width, height);
g2d.setFont(new Font("宋体", Font.BOLD, 18));
Random random=new Random();
for(int i=0;i<4;i++)//获取随机四个汉字
{
Color c=new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
String s=GetStr(); AffineTransform aff = new AffineTransform();
aff.rotate(Math.random(),i*10,height-20);//旋转
aff.scale(0.2+Math.random(), 0.2+Math.random());//缩放
g2d.setTransform(aff);
System.err.println(">:"+s); g2d.setColor(c);
g2d.drawString(s, i*10, height- 5);
} for(int i=0;i<3;i++) //干扰线
{
Color c=new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
g2d.setColor(c);
g2d.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height)); }
g2d.dispose();//图片生效
ImageIO.write(image, "jpeg", response.getOutputStream());//输出
System.out.println("输出");
} //获取汉字
private static String GetStr()
{
String str = null;
try { int hightPos, lowPos; // 定义高低位
Random random = new Random();
hightPos = (176 + Math.abs(random.nextInt(39)));//获取高位值
lowPos = (161 + Math.abs(random.nextInt(93)));//获取低位值
byte[] b = new byte[2];
b[0] = (new Integer(hightPos).byteValue());
b[1] = (new Integer(lowPos).byteValue());
str = new String(b, "GBK");//转成中文 } catch (Exception e) {
e.printStackTrace();
}
return str; }

PS:写验证码不能把所有的都用上,这样就无法识别了,可以选择其中的几种进行,如写汉字只加干扰线,写字母加旋转等。

上一篇:BottomSheetBehavior 之 java.lang.IllegalArgumentException: The view is not associated with BottomSheetBehavior


下一篇:DB查询分析器访问EXCEL时,要在表名前后加上中括弧或双引号