package net.hncu.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.LinkedList;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class Yanzhengma {
public String sRand = "";
public Yanzhengma() {
}
// 给定范围获得随机颜色
public Color getRandColor(int fc, int bc) {
Random random = new Random();
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);
}
//创建图像 格式为jpg类型,默认长和宽
public BufferedImage getBufferedImage(String content) {
int width = 60, height = 20;
return getBufferedImage(content, width, height);
}
//创建图像 格式为jpg类型,接受长和宽两个参数
public BufferedImage getBufferedImage(String content, int width, int height) {
// 实例化BufferedImage
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics2D g = image.createGraphics();
// 生成随机类
Random random = new Random();
// 设定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 设定字体
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
// 设置字体颜色
g.setColor(Color.black);
g.drawString(content, 10, 15);
g.dispose();
//返回图片
return image;
}
// 返回一个4位的验证码
public String getContent() throws InterruptedException {
String content = "";
for (int i = 0; i < 4; i++) {
content += getChar();
//利用 休眠以控制字符的重复问题
Thread.sleep(new Random().nextInt(10) + 10);
}
return content;
}
//获取随机字符
public char getChar() {
Random random = new Random();
char ch = '0';
LinkedList ls = new LinkedList();
for (int i = 0; i < 10; i++) {// 0-9
ls.add(String.valueOf(48 + i));
}
for (int i = 0; i < 26; i++) {// A-Z
ls.add(String.valueOf(65 + i));
}
for (int i = 0; i < 26; i++) {// a-z
ls.add(String.valueOf(97 + i));
}
int index = random.nextInt(ls.size());
if (index > (ls.size() - 1)) {
index = ls.size() - 1;
}
ch = (char) Integer.parseInt(String.valueOf(ls.get(index)));
return ch;
}
}
- 1
- 2
前往页