通过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);
}


}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值