java如何製作驗證碼
阿新 • • 發佈:2018-12-19
1---jsp
<body>
<img src="YanZhangma" >
</body>
2----servlet
package com.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class YanZhangma extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//定義一個隨機數的陣列
String[] str={"1","2","h","w","y","8","t","0","a","g"};
//定義寬和高
int height=50,width=100;
//得到畫布
BufferedImage image=new BufferedImage (width,height, BufferedImage.TYPE_3BYTE_BGR);
//建立畫筆
Graphics g=image.getGraphics();
//設定矩形背景色
g.setColor(Color.yellow);
//製作矩形背景
g.fillRect(0, 0,width, height);
//設定邊框顏色
g.setColor(Color.red);
//設定邊框
g.drawRect(0, 0, width-1, height-1);
//產生隨機數
String str1="";
Random rand=new Random();
for(int i=0;i<4;i++){
//產生1-10 得到陣列的下標
int num=rand.nextInt(10);
str1+=str[num];
}
//設定字型
g.setFont(new Font("宋體",Font.BOLD,30));
g.drawString(str1, 20, 20);
//設定顏色
g.setColor(Color.green);
//寫入畫布
//寫一些點干擾
//設定顏色
g.setColor(Color.black);
for(int i=0;i<15;i++){
g.fillOval(rand.nextInt(60), rand.nextInt(20), 2, 2);
}
//建立輸入流物件
OutputStream out=resp.getOutputStream();
//建立圖片IO流
ImageIO.write(image, "jpg", out);
}
}