package com.servlet;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import com.sun.org.apache.bcel.internal.generic.NEW;
public class VCode {
Random random=new Random();
private int w=70;//宽
private int h=35;//高
//private Color bgColor=new Color(240,240,240);
private StringBuilder code=new StringBuilder(4);
private BufferedImage createImage() {
/**
* 1创建图片
* 2设置背景颜色
*/
//创建图片
BufferedImage img=new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
//设置画笔颜色
Graphics g =img.getGraphics();
g.setColor(this.randomColor());
//填充一个与图片一样大小的矩形!即设置背景颜色。
g.fillRect(0, 0, 70, 35);
return img;
}
//随机颜色
private Color randomColor() {
int r=random.nextInt(256);
int b=random.nextInt(256);
int g=random.nextInt(256);
return new Color(r,b,g);
}
/**
* 字体名、样式、字号
*/
private String[] fontNames={"宋体","华文楷体","黑体","华文新魏","华文隶书","微软雅黑","楷体_GB2312"};
//private int[] fontStyles={0,1,2,3};
private int[] fontSizes={24,25,26,27,28};//字号范围
//随机字体
private Font randomFont(){
int index=random.nextInt(fontNames.length);//如果数组长度为7,数值为0~6,合法下标
String name=fontNames[index];
int style=random.nextInt(4);//0,1,2,3
index=random.nextInt(fontSizes.length);
int size=fontSizes[index];
return new Font(name,style,size);
}
//随机生成字符
private String codes="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private String randomChar() {
int index=random.nextInt(codes.length());
return codes.charAt(index)+"";
}
//随机生成干扰线
private void drawLine(BufferedImage img) {
Graphics2D g=(Graphics2D)img.getGraphics();
g.setColor(Color.black);
g.setStroke(new BasicStroke(1.5F));
for(int i=0;i<5;i++){
int x1=random.nextInt(w);
int y1=random.nextInt(h);
int x2=random.nextInt(w);
int y2=random.nextInt(h);
g.drawLine(x1, y1, x2, y2);
}
}
//用户调用这个方法获取图片
public BufferedImage getImage() {
/**
* 字符、字体、颜色随机
*/
BufferedImage img=createImage();
Graphics g=img.getGraphics();
//画东西
for(int i=0;i<4;i++){
String ch=this.randomChar();//获取随机字符
code.append(ch);//记录生成的字符
g.setColor(this.randomColor());//随机颜色
g.setFont(this.randomFont());//随机字体
g.drawString(ch, w/4*i, h-5);
}
this.drawLine(img);//添加干扰线
return img;
}
//这个方法必须在getImage()方法之后调用
public String getCode(){
return code.toString();
}
//保存图片
public static void saveImage(BufferedImage img,OutputStream out) throws IOException {
ImageIO.write(img, "JPEG", out);
}
}
java生成验证码图片
最新推荐文章于 2021-11-18 10:30:04 发布