最近在做一个面试题,断断续续地忙了九天。终于赶在圣诞节前,这个美好的晚上完成。不仅把SSH架构复习一遍,displaytag也应用上了。
完成这个项目,产生了几个衍生品。其中验证码就是其中一个。
一般大登录和注册页面上存在验证,以前觉得很神秘。可能是接触得多,高度就高了,再看验证码,其实就是response一个contentType="image/jpeg"类型的html而已。
下面是我和awt方式生成这张图片的源码:
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class Test extends Frame {
public Test() {
Button b = new Button("下一个");
setBounds(300, 300, 400, 400);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
});
repaint();
this.setLayout(new BorderLayout());
this.add(b, BorderLayout.SOUTH);
this.setVisible(true);
}
@Override
public void paint(Graphics headG) {
int width = 400, height = 400;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Arial", Font.BOLD, 120));
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 550; 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 sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
g.setColor(new Color(0, 0, 0));
g.drawString(rand, 110 * i + 3, 250);
}
headG.drawImage(image, 0, 0, this);
}
public static void main(String[] args) {
new Test();
}
static 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);
}
}
运行情况(截图):
|