当前位置: 代码迷 >> Web前端 >> 透过response输出认证图片
  详细解决方案

透过response输出认证图片

热度:187   发布时间:2012-11-16 14:12:14.0
通过response输出认证图片
package com.hbsi.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;


public class Response3 extends HttpServlet {


private static final int WIDTH=130;
private static final int HEIGHT=30;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1.创建图片
BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_3BYTE_BGR);
//2.得到图片
Graphics g = image.getGraphics();
//3.对图片进行绘制

//a.设置图片的背景色
setBackGround(g);

//b.设置矩形边框
setBorder(g);

//c.添加干扰线
setRandomLine(g);

//d.向图形中写数据
setRandomNum(g);

//4.把图片写给浏览器
//用下边较短的语句代替response.setHeader("content-type", "image/jpeg");
response.setContentType("image/jpeg");
ImageIO.write(image,"JPEG",response.getOutputStream());
//
}


private void setRandomNum(Graphics g) {
g.setColor(Color.BLACK);
g.setFont(new Font("宋体",Font.BOLD,20));
Random random = new Random();

int x=10;
for(int i=0;i<4;i++){
//产生随机数
String str = String.valueOf(random.nextInt(10));
//把数写在图片上
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));

int degree = random.nextInt()%30;
((Graphics2D)g).rotate(degree*Math.PI/180, x, 20);
g.drawString(str, x, 20);
((Graphics2D)g).rotate(-degree*Math.PI/180, x, 20);
x+=30;

}

}


private void setRandomLine(Graphics g) {
g.setColor(Color.green);
Random random = new Random();
for(int i=0;i<5;i++){
int x1 = random.nextInt(WIDTH);
int y1 = random.nextInt(HEIGHT);

int x2 = random.nextInt(WIDTH);
int y2 = 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);

}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


doGet(request, response);
}


}



  相关解决方案