欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

关于java 图形验证码的解决方法

程序员文章站 2023-12-13 23:16:22
复制代码 代码如下:package cn.response; import java.awt.color;import java.awt.font;import java...

复制代码 代码如下:

package cn.response;

import java.awt.color;
import java.awt.font;
import java.awt.graphics;
import java.awt.graphics2d;
import java.awt.image.bufferedimage;
import java.io.ioexception;
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;

@suppresswarnings("serial")
public class validatepicture extends httpservlet {

 public void doget(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  try {
   validateimage(request, response);
  } catch (exception e) {
   e.printstacktrace();
  }
 }

 public void dopost(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  doget(request, response);
 }

 public static final int width = 120;
 public static final int height = 25;

 public void validateimage(httpservletrequest request,
   httpservletresponse response) throws exception {

  bufferedimage bi = new bufferedimage(width, height,
    bufferedimage.type_int_rgb);// 在内存中构建一幅图象
  graphics g = bi.getgraphics();

  setbackground(g);// 设置背景色
  setborder(g);// 设置边框
  drawrandomline(g);// 画干扰线
  string random = drawrandomnum((graphics2d) g);// 写随机数

  request.getsession().setattribute("random", random);
  //request.getsession(false);
  response.setcontenttype("image/jpeg");
  // 设置不要缓存
  response.setdateheader("expries", -1);
  response.setheader("cache-control", "no-cache");

  imageio.write(bi, "jpg", response.getoutputstream());
 }

 private string drawrandomnum(graphics2d g) {
  g.setcolor(color.red);
  g.setfont(new font("宋体", font.bold, 20));
  // [\u4e00-\u9fa5]中文数字区间
  string base = "\u4e00\u4f00\u5e00\u4e50\u4e89\u4f10\u4e09";

  stringbuffer sb = new stringbuffer();

  int x = 5;
  for (int i = 0; i < 4; i++) {
   int degree = new random().nextint() % 30;

   string ch = base.charat(new random().nextint(base.length())) + "";
   sb.append(ch);
   g.rotate(degree * math.pi / 180, x, 20);
   g.drawstring(ch, x, 20);
   g.rotate(-degree * math.pi / 180, x, 20);

   x = x + 30;
  }
  system.out.println(sb.tostring());
  return sb.tostring();
 }

 private void drawrandomline(graphics g) {
  g.setcolor(color.green);
  for (int i = 0; i < 3; i++) {
   int x1 = new random().nextint(width);
   int y1 = new random().nextint(height);

   int x2 = new random().nextint(width);
   int y2 = new random().nextint(height);

   g.drawline(x1, y1, x2, y2);
  }
 }

 private void setborder(graphics g) {
  g.setcolor(color.blue);
  g.drawrect(1, 1, width - 2, height - 2);
 }

 private void setbackground(graphics g) {
  g.setcolor(color.white);
  g.fillrect(0, 0, width, height);
 }
}

上一篇:

下一篇: