前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。
1.生成工具类;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.util.Random;import javax.imageio.ImageIO;/*** 登陆图形验证码生成工具类* @author JiangYu*/
public class ImageCreate {public static void main(String[] args)throws Exception {//测试new ImageCreate().create(); }//验证码字符串private String codeV;public String getCode() {return codeV;}//生成验证码public BufferedImage create() throws Exception {// 大小int width = 120;int height = 30;/** Image是一个抽象列,BufferedImage是Image的实现。* Image和BufferedImage的主要作用就是将一副图片加载到内存中。*/// 声明一个 RGB格式图片:图片类型为rgbBufferedImage img = new BufferedImage(width, height,BufferedImage.TYPE_INT_BGR);// 获取画笔Graphics g = img.getGraphics();// 背景色g.setColor(Color.WHITE);// 画g.fillRect(0, 0, width, height);// 字体g.setFont(new Font("黑体", Font.BOLD, 18));//为codeV传值 String d ="";// 写一个字符到imgRandom r = new Random();for (int i = 0; i < 4; i++) {//生成随机字母 String chars = "ABCDEFGHJKMNOPQRSTUVWXYZ";char codeEnglish = chars.charAt((int)(Math.random() * 24));d += codeEnglish;codeV = d;// 画笔随机色g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));// 写出字符g.drawString("" + codeEnglish, i * 30, 10 + r.nextInt(20)); }//干扰线for(int i=0;i<4;i++){g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));//画线g.drawLine(r.nextInt(120), r.nextInt(30), r.nextInt(120), r.nextInt(30));}//图片生成g.dispose();//设置路径: 路径要用到转义\\
// ImageIO.write(img,"JPEG", new FileOutputStream("H:\\JiangYu\\YanZhengImages\\yanZhengImage.jpg"));return img;}
}
2. 调用方法:
/*** 生成图形验证码* @param request* @param response* @throws Exception*/@RequestMapping(value="/getCode")public void getCode(HttpServletRequest request,HttpServletResponse response) throws Exception {ImageCreate i = new ImageCreate();//发送图片 ImageIO.write(i.create(), "JPEG", response.getOutputStream()); //验证码字符 String code = i.getCode().toString(); request.getSession().setAttribute("code", code);}
3. jsp 页面:
<div style="margin-bottom: 20px"><input id="code" name="code" type="text" class="easyui-textbox" style="width: 39%;height: 40px; padding: 12px" data-options="prompt:'验证码',iconWidth:38" /><!-- 1.浮动提示框效果:easyui-tooltip、2.如果无法显示图像,浏览器将显示替代文本:alt属性 --><a href="#" title="看不清,点击换一下" class="easyui-tooltip"><img onclick="change()" class="easyui-linkbutton" src="/getCode" id="vimg" alt="" style="height: 40px;" /></a></div>
//看不清,点击换一下function change() {//图片对象var imgNode = document.getElementById("vimg");$.ajax({url:"/getCode",type:"post",success:function(data){//改变src属性值 imgNode.src="/getCode?t=" + (new Date()).valueOf();},error:function(){alert(" 验证码图片路径获取失败 !");}});}