一个Java类:
package com.abc.ufo.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.OutputStream; import java.util.Random; import javax.imageio.ImageIO; public class ImageMaker{ private char map[]={‘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‘,‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘7‘,‘8‘,‘9‘}; public String getImage(int width,int height,OutputStream os){ 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); StringBuilder sb=new StringBuilder(); for(int i=0;i<4;i++){ sb.append(map[(int)(map.length*Math.random())]); } String text=sb.toString(); g.setColor(Color.black); g.setFont(new Font("Arial",Font.PLAIN,36)); g.setColor(Color.red); String str=text.substring(0,1); g.drawString(str, 18, 32); g.setColor(Color.blue); str=text.substring(1,2); g.drawString(str, 60, 32); g.setColor(Color.red); str=text.substring(2,3); g.drawString(str, 95, 32); g.setColor(Color.blue); str=text.substring(3,4); g.drawString(str, 125, 32); g.setColor(Color.gray); Random rand=new Random(); for(int i=0;i<20;i++){ int x=rand.nextInt(width); int y=rand.nextInt(height); g.drawOval(x, y, width, height); } g.setColor(Color.black); g.drawRect(0, 0, width-1, height-1); //g.drawLine(width-2, 0, width-2, height); g.dispose(); try{ ImageIO.write(image, "JPEG", os); }catch(Exception e){ //e.printStackTrace(); } return text; } }
JSP:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page contentType="image/jpeg" %> <jsp:useBean id="image" scope="page" class="com.abc.ufo.util.ImageMaker"/> <% String str=image.getImage(160,40,response.getOutputStream()); session.setAttribute("verifyCode",str); out.clear(); out = pageContext.pushBody(); %>
页面使用:
<div class="page-container"> <logic:present name="error"> <h2><bean:write name="error"/></h2> </logic:present> <h1>Login</h1> <form action="login.html" method="post"> <input type="text" id="usernameTxt" name="username" class="username" placeholder="Username"> <input type="password" id="passwordTxt" name="password" class="password" placeholder="Password"> <input type="text" id="verifyCodeTxt" name="verifyCode" class="verifyCode" placeholder="Verification code"> <p><br/>No Zero in the verification code</p> <img src="pages/user/login/image.jsp"/> <!-- 这个路径就是前面jsp的路径 --> <button id="submitBtn">Sign me in</button> <div class="error"><span>+</span></div> </form> <div class="connect" style="display:none"> <p>Or connect with:</p> <p> <a class="facebook" href=""></a> <a class="twitter" href=""></a> </p> </div> </div>
页面效果:
时间: 2024-09-30 04:21:25