java生成圖片驗證碼
packageutil;
importjava.awt.Color;
importjava.awt.Font;
importjava.awt.Graphics;
importjava.awt.image.BufferedImage;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.util.Random;
importjavax.imageio.ImageIO;
publicfinalclassImageUtil{
//驗證碼字元集
privatestaticfinalchar[]chars={
'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
'O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z'};
//字元數量
privatestaticfinalintSIZE=4;
//干擾線數量
privatestaticfinalintLINES=5;
//寬度
privatestaticfinalintWIDTH=80;
//高度
privatestaticfinalintHEIGHT=40;
//字體大小
privatestaticfinalintFONT_SIZE=30;
/**
*生成隨機驗證碼及圖片
*返回的數組中,第1個值是驗證碼,第2個值是圖片
*/
publicstaticObject[]createImage(){
StringBuffersb=newStringBuffer();
//1.創建空白圖片
BufferedImageimage=newBufferedImage(
WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
//2.獲取圖片畫筆
Graphicsgraphic=image.getGraphics();
//3.設置畫筆顏色
graphic.setColor(Color.LIGHT_GRAY);
//4.繪制矩形背景
graphic.fillRect(0,0,WIDTH,HEIGHT);
//5.畫隨機字元
Randomran=newRandom();
for(inti=0;i<SIZE;i++){
//取隨機字元索引
intn=ran.nextInt(chars.length);
//設置隨機顏色
graphic.setColor(getRandomColor());
//設置字體大小
graphic.setFont(newFont(
null,Font.BOLD+Font.ITALIC,FONT_SIZE));
//畫字元
graphic.drawString(
chars[n]+"",i*WIDTH/SIZE,HEIGHT/2);
//記錄字元
sb.append(chars[n]);
}
//6.畫干擾線
for(inti=0;i<LINES;i++){
//設置隨機顏色
graphic.setColor(getRandomColor());
//隨機畫線
graphic.drawLine(ran.nextInt(WIDTH),ran.nextInt(HEIGHT),
ran.nextInt(WIDTH),ran.nextInt(HEIGHT));
}
//7.返回驗證碼和圖片
returnnewObject[]{sb.toString(),image};
}
/**
*隨機取色
*/
(){
Randomran=newRandom();
Colorcolor=newColor(ran.nextInt(256),
ran.nextInt(256),ran.nextInt(256));
returncolor;
}
publicstaticvoidmain(String[]args)throwsIOException{
Object[]objs=createImage();
BufferedImageimage=(BufferedImage)objs[1];
OutputStreamos=newFileOutputStream("d:/1.png");
ImageIO.write(image,"jpeg",os);
os.close();
}
}
B. 求java語言隨機生成圖片驗證碼的程序代碼,有詳細注釋最好,本人初學者,謝謝各位的幫忙!!!
樓上正解
/**
*圖片驗證碼
*
*@authorHuangYong
*
*/
{
=1532787236715859525L;
/**
*驗證圖片寬
*/
privatestaticfinalintWIDTH=80;
/**
*驗證圖片高度
*/
privatestaticfinalintHEIGHT=20;
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
//獲得圖片
BufferedImageimage=newBufferedImage(WIDTH,HEIGHT,
BufferedImage.TYPE_INT_RGB);
//獲取畫筆
Graphicsg=image.getGraphics();
//設置邊框
setBounds(g);
////設置背景
//setBackGround(g);
//干擾線
drawRandomLine(g);
//驗證碼
drawRandomString((Graphics2D)g,request);
//發送給頁面
response.setContentType("image/jpeg");
response.setDateHeader("expries",-1);
response.setHeader("cache-control","no-cache");
response.setHeader("progma","no-cache");
ImageIO.write(image,"jpg",response.getOutputStream());
}
/**
*邊框
*
*@paramg
*/
privatevoidsetBounds(Graphicsg){
g.setColor(Color.BLUE);
g.fillRect(0,0,WIDTH,HEIGHT);
g.setColor(Color.WHITE);
g.fillRect(1,1,WIDTH-2,HEIGHT-2);
}
/**
*背景
*
*@paramg
*/
//privatevoidsetBackGround(Graphicsg){
//
//g.setColor(Color.WHITE);
//g.drawRect(1,1,WIDTH-2,HEIGHT-2);
//
//}
/**
*干擾線
*
*@paramg
*/
privatevoiddrawRandomLine(Graphicsg){
g.setColor(Color.GREEN);
intx1,y1;
intx2,y2;
Randomr=newRandom();
for(inti=0;i<5;i++){
//起始xy
x1=r.nextInt(WIDTH);
y1=r.nextInt(HEIGHT);
//結束xy
x2=r.nextInt(WIDTH);
y2=r.nextInt(HEIGHT);
g.drawLine(x1,y1,x2,y2);
}
}
/**
*驗證碼
*
*@paramg
*/
privatevoiddrawRandomString(Graphics2Dg,HttpServletRequestrequest){
g.setColor(Color.RED);
g.setFont(newFont("宋體",Font.BOLD,20));
Stringbase="";
StringBuildersb=newStringBuilder();
charch='u0000';
intdegree=0;
Randomr=newRandom();
intstartX=8;
for(inti=0;i<4;i++){
ch=base.charAt(r.nextInt(base.length()));
//設置旋轉,±20°
degree=r.nextInt()%20;
g.rotate(degree*Math.PI/180,startX,14);
g.drawString(ch+"",startX,16);
//取消旋轉
g.rotate(-degree*Math.PI/180,startX,14);
startX+=18;
sb.append(ch);
}
request.getSession().setAttribute("checkCode",sb.toString().toLowerCase());
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doGet(request,response);
}
希望能幫助你
C. 求一篇用java生成的驗證碼程序。。。
把生成驗證碼圖片的程序封裝為一個JavaBean,這個JavaBean的源代碼如下:
makeCertPic.java
package pic;
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;
/**
* @author dzy
* 生成驗證碼圖片
*/
public class makeCertPic {
//驗證碼圖片中可以出現的字元集,可根據需要修改
private char mapTable[]={
'a','b','c','d','e','f',
'g','h','i','j','k','l',
'm','n','o','p','q','r',
's','t','u','v','w','x',
'y','z','0','1','2','3',
'4','5','6','7','8','9'};
/**
* 功能:生成彩色驗證碼圖片
* 參數width為生成圖片的寬度,參數height為生成圖片的高度,參數os為頁面的輸出流
*/
public String getCertPic(int width, int height, OutputStream os) {
if(width<=0)width=60;
if(height<=0)height=20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 獲取圖形上下文
Graphics g = image.getGraphics();
// 設定背景色
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);
//畫邊框
g.setColor(Color.black);
g.drawRect(0,0,width-1,height-1);
// 取隨機產生的認證碼
String strEnsure = "";
// 4代表4位驗證碼,如果要生成更多位的認證碼,則加大數值
for(int i=0; i<4; ++i) {
strEnsure+=mapTable[(int)(mapTable.length*Math.random())];
}
// 將認證碼顯示到圖像中,如果要生成更多位的認證碼,增加drawString語句
g.setColor(Color.black);
g.setFont(new Font("Atlantic Inline",Font.PLAIN,18));
String str = strEnsure.substring(0,1);
g.drawString(str,8,17);
str = strEnsure.substring(1,2);
g.drawString(str,20,15);
str = strEnsure.substring(2,3);
g.drawString(str,35,18);
str = strEnsure.substring(3,4);
g.drawString(str,45,15);
// 隨機產生10個干擾點
Random rand = new Random();
for (int i=0;i<10;i++) {
int x = rand.nextInt(width);
int y = rand.nextInt(height);
g.drawOval(x,y,1,1);
}
// 釋放圖形上下文
g.dispose();
try {
// 輸出圖像到頁面
ImageIO.write(image, "JPEG", os);
} catch (IOException e) {
return "";
}
return strEnsure;
}
} 在getCertPic()方法中,首先創建了一個內存圖像的實例對象,再得到此內存圖像的圖形上下文對象,接著再用這個上下文對象畫背景、邊框。接下來,隨機生成4個在mapTable[]數組中的字元,組成字元串作為驗證字元串,並輸出在內存中,為了造成一定的干擾,隨機畫了10個干擾點,如果要加大幹擾效果,可再多畫一些點。
makeCertPic.jsp頁面用於調用生成驗證碼圖片的JavaBean,並在客戶端顯示,源代碼如下:
makeCertPic.jsp
<%@page contentType="image/jpeg" %>
<jsp:useBean id="image" scope="page" class="pic.makeCertPic" />
<%
Stringstr=image.getCertPic(0,0,response.getOutputStream());
// 將認證碼存入SESSION
session.setAttribute("certCode", str);
%>這里把生成的驗證碼作為session變數寫入,因此在接收登錄頁面輸入的數據頁面中,可用用戶輸入的驗證碼和這個session變數作比較,如果相同則表示驗證通過。
LoginPic.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<html>
<head><title>登錄頁面</title></head>
<body>
<table align="center" border="0">
<tralign="center"><td><fontcolor="red"><html:errors/></font></td></tr>
<tr align="center"><td>系統登錄</td></tr>
<form. action="loginCheck.jsp" method="post" focus="username">
<tr><td>用戶名:<input type="text" name="username"/></td></tr>
<tr><td>密 碼:<input type="password"name="password"/></td></tr>
<tr><td>驗證碼:<input type="text" name="certCode"/>
<img src="makeCertPic.jsp">
</td></tr>
<tralign="left"><td>
<input type="submit" value="確定"/></td></tr>
</form>
</table>
</body>
</html> 驗證碼的輸入是否正確可用如下語句驗證:
String certCode=request.getParameter("certCode");
if(certCode.equals((String)session.getAttribute("certCode")))
out.print("驗證碼輸入正確");
else
out.print("驗證碼輸入錯誤");
D. 如何在java中生成驗證碼在頁面生成
以下是我寫的生成的圖片驗證碼
//調用驗證碼生成並把驗證碼返回頁面
Map<String,BufferedImage>imageMap=ImageUtil.createImage();
Stringcode=imageMap.keySet().iterator().next();
session.setAttribute("imageCode",code);
BufferedImageimage=imageMap.get(code);
response.setContentType("image/jpeg");
OutputStreamops=response.getOutputStream();
ImageIO.write(image,"jpeg",ops);
ops.close();
//生成驗證碼工具類
publicfinalclassImageUtil{
privatestaticfinalchar[]chars={'A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T','U','V','W',
'X','Y','Z','0','1','2','3','4','5','6','7','8','9'};
privatestaticfinalintSIZE=4;
privatestaticfinalintLINES=5;
privatestaticfinalintWIDTH=80;
privatestaticfinalintHEIGHT=40;
privatestaticfinalintFONT_SIZE=30;
publicstaticMap<String,BufferedImage>createImage(){
StringBuffersb=newStringBuffer();
BufferedImageimage=newBufferedImage(WIDTH,HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphicsgraphic=image.getGraphics();
graphic.setColor(Color.LIGHT_GRAY);
graphic.fillRect(0,0,WIDTH,HEIGHT);
Randomran=newRandom();
//畫隨機字元
for(inti=1;i<=SIZE;i++){
intr=ran.nextInt(chars.length);
graphic.setColor(getRandomColor());
graphic.setFont(newFont(null,Font.BOLD+Font.ITALIC,FONT_SIZE));
graphic.drawString(chars[r]+"",(i-1)*WIDTH/SIZE,HEIGHT/2);
sb.append(chars[r]);
}
//畫干擾線
for(inti=1;i<=LINES;i++){
graphic.setColor(getRandomColor());
graphic.drawLine(ran.nextInt(WIDTH),ran.nextInt(HEIGHT),
ran.nextInt(WIDTH),ran.nextInt(HEIGHT));
}
Map<String,BufferedImage>map=newHashMap<String,BufferedImage>();
map.put(sb.toString(),image);
returnmap;
}
(){
Randomran=newRandom();
Colorcolor=newColor(ran.nextInt(256),ran.nextInt(256),ran.nextInt(256));
returncolor;
}
(BufferedImageimage)
throwsIOException{
ByteArrayOutputStreambos=newByteArrayOutputStream();
JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(bos);
encoder.encode(image);
byte[]imageBts=bos.toByteArray();
InputStreamin=newByteArrayInputStream(imageBts);
returnin;
}
}
E. JAVA識別圖片驗證碼
package com.he;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
public class CodeFact
extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
//設置頁面不緩存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 在內存中創建圖象
int width = 60, height = 20;
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("Times New Roman", Font.PLAIN, 18));
//畫邊框
g.setColor(new Color(33,66,99));
g.drawRect(0,0,width-1,height-1);
// 隨機產生155條干擾線,使圖象中的認證碼不易被其它程序探測到
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; 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);
}
// 取隨機產生的認證碼(4位數字)
String sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
// 將認證碼顯示到圖象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110),
20 + random.nextInt(110))); //調用函數出來的顏色相同,可能是因為種子太接近,所以只能直接生成
g.drawString(rand, 13 * i + 6, 16);
}
// 將認證碼存入SESSION
HttpSession session = request.getSession();
session.setAttribute("rand", sRand);
// 圖象生效
g.dispose();
// 輸出圖象到頁面
ImageIO.write(image, "JPEG", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//給定范圍獲得隨機顏色
private 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);
}
}
你試試!!
F. 用java隨機生成四位驗證碼,只求編程代碼
不知道你問的是不是生成這種圖片驗證碼?
如果只要一個隨機四位數 那這行代碼就夠了(new Random().nextInt(9000) + 1000;),
如果是生成頁面圖片驗證碼就是下面的了:
//設定 響應模式
resp.setContentType("image/jpeg");
// 生成令牌環數據;
Integer token = new Random().nextInt(9000) + 1000;
// 保存令牌環數據到session中
req.getSession().setAttribute(IMAGE_TOKEN_NAME, token);
// 生成令牌環圖片
ServletOutputStream out = resp.getOutputStream();
BufferedImage img = new BufferedImage(60, 20,
BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.YELLOW);
g.fillRect(0, 0, img.getWidth(), img.getHeight());
g.setColor(Color.BLUE);
g.setFont(new Font("", Font.BOLD, 18));
g.drawString(String.valueOf(token), 10, 16);
ImageIO.write(img, "jpg", out);
out.close();
G. 如何用java取出隨機生成的驗證碼圖片里的數字
為什麼要放在session.太浪費資源。放在request裡面。每次請求的時候後台生成一個新的數字就request.setAttribult,頁面getAtrribult就可以了。你網路下用法就懂了
H. java怎麼生成驗證碼圖片
以下僅供參考:
這是jsp頁面,起個名字例如叫image.jsp:
<%@ page contentType="image/JPEG"
import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"
pageEncoding="GBK"%><%!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);
}%><%
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
int width = 60, height = 20;
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("Times New Roman", Font.PLAIN, 18));
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 100; 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(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
session.setAttribute("code", sRand);
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
%>
在你需要引入的地方:
<img border=0 src="image.jsp">
就可以了。。。
I. java生成圖形驗證碼成符號了怎麼回事
AuthImage類:
[java] view plain
package hh.com.util;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;