【Java开源代码栏目提醒】:网学会员--在 Java开源代码编辑为广大网友搜集整理了:Code_MakerServle.java绩等信息,祝愿广大网友取得需要的信息,参考学习。
package chp20;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
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 Code_MakerServle extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 首先设置页面不缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 定义图片的宽度和高度
int width = 90, height = 40;
// 创建一个图像对象
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();// 得到图像的绘制环境
Random random = new Random();
// 用随机颜色填充图像背景
g.setColor(getRandColor(180, 250));
g.fillRect(0, 0, width, height);
for (int i = 0; i < 6; i++) {
g.setColor(getRandColor(50, 100));
int x = random.nextInt(width);
int y = random.nextInt(height);
g.drawOval(x, y, 5, 5);
}
g.setFont(new Font("", Font.PLAIN, 40)); // 设置字体,下面准备画随机数
String sRand = ""; // 随机数字符串
for (int i = 0; i < 4; i++) {
// 生成四个数字字符
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
// 生成随机颜色
g.setColor(new Color(20 + random.nextInt(80), 20 + random
.nextInt(100), 20 + random.nextInt(90)));
// 将随机数字画在图像上
g.drawString(rand, (17 + random.nextInt(3)) * i + 8, 34);
// 生成干扰线
for (int k = 0; k < 12; k++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(9);
int yl = random.nextInt(9);
g.drawLine(x, y, x + xl, y + yl);
}
}
// 将生成的随机数字字符串写入session
request.getSession().setAttribute("randomNumber", sRand);
g.dispose(); // 使图像生效
ImageIO.write(image, "JPEG", response.getOutputStream()); // 输出图像到页面
}
// 产生一个随机的颜色 其中,min:颜色分量最小值 ;max:颜色分量最大值
public Color getRandColor(int min, int max) {
Random random = new Random();
if (min > 255) {
min = 255;
}
if (max > 255) {
max = 255;
}
int R = min + random.nextInt(max - min);
int G = min + random.nextInt(max - min);
int B = min + random.nextInt(max - min);
return new Color(R, G, B);
}
}