⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 randimg.java

📁 jsp超市管理系统系统,是用经典的MVC设计模式开发的非常适合初学者学习。
💻 JAVA
字号:
package com.mybean;

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import javax.imageio.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RandImg extends HttpServlet{		
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -7697665114296443721L;
		// 产生随机颜色函数getRandColor
		Color getRandColor(int fc, int bc){
				Random r = new Random();
				if (fc > 255)
					fc = 255;
				if (bc > 255)
					bc = 255;
				int red = fc + r.nextInt(bc - fc); // 红
				int green = fc + r.nextInt(bc - fc); // 绿
				int blue = fc + r.nextInt(bc - fc); // 蓝
				return new Color(red, green, blue);
			}
		
		@Override
		public void service(HttpServletRequest req, HttpServletResponse res)
				throws ServletException, IOException{

				// 阻止生成的页面内容被缓存,保证每次重新生成随礼验证码
				res.setHeader("Pragma", "No-cache");
				res.setHeader("Cache-Control", "no-cache");
				res.setDateHeader("Expires", 0);
				res.setContentType("image/jpeg");
				// 创建随机类
				Random r = new Random();
				
				// 在内存中创建图像,宽度为width,高度为height
				int width = 60, height = 20;
				BufferedImage pic = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
				
				// 获取图形上下文环境
				Graphics gc = pic.getGraphics();
				
				// 设定背景色并进行填充
				gc.setColor(getRandColor(200, 250));
				gc.fillRect(0, 0, width, height);
				// 设定图形上下文环境字体
				gc.setFont(new Font("Times New Roman", Font.PLAIN, 18));
				// 随机产生200条干扰直线,使图像中的认证码不易被其他分析程序探测到
				gc.setColor(getRandColor(160, 200));
				for(int i = 0; i < 200; i++){
						int x1 = r.nextInt(width);
						int y1 = r.nextInt(height);
						int x2 = r.nextInt(15);
						int y2 = r.nextInt(15);
						gc.drawLine(x1, y1, x1 + x2, y1 + y2);
				}
				// 随机产生100个干扰点,使图像中的验证码不易被其他分析程序探测到
				gc.setColor(getRandColor(120, 240));
				for(int i = 0; i < 100; i++){
						int x = r.nextInt(width);
						int y = r.nextInt(height);
						gc.drawOval(x, y, 0, 0);
				}
				
				// 随机产生4位数字的验证码
				String RS = "";
				String rn = "";
				for(int i = 0; i < 4; i++){
						// 产生10以内随机数字rn
						rn = String.valueOf(r.nextInt(10));
						RS += rn;
						// 将认证码用drawString函数显示到图像里
						gc.setColor(new Color(20 + r.nextInt(110), 20 + r
								.nextInt(110), 20 + r.nextInt(110)));
						gc.drawString(rn, 13 * i + 6, 16);
				}
				
				// 释放图形上下文环境
				gc.dispose();
				
				// 输出生成后的验证码图像到页面
				ImageIO.write(pic, "JPEG", res.getOutputStream());
				// 将认证码RS存入SESSION中共享
				req.getSession(true).setAttribute("random", RS);
			}
		
	}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -