产生随机数图片

来源:互联网 发布:ssr linux 客户端配置 编辑:程序博客网 时间:2024/05/22 15:40
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获得一张图片// 创建图片 -- 在内存中int width = 80;int height = 40;BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//创建图层,获得画板Graphics g = image.getGraphics();//确定画笔颜色g.setColor(Color.BLACK);//填充一个矩形g.fillRect(0, 0, width, height);//只需要一个边框//设置颜色g.setColor(Color.WHITE);//填充一个矩形g.fillRect(1, 1, width -2, height -2);//填充字符String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";//设置字体g.setFont(new Font("宋体",Font.BOLD,30));//缓存随机生成的字符StringBuffer buf = new StringBuffer();//随机获得4个字符Random random = new Random();for(int i = 0 ; i < 4 ; i++){//设置随机颜色g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));//获得一个随机字符int index = random.nextInt(62);//截取字符串String str = data.substring(index, index + 1);  //[)//需要将随机的字符,写到图片中g.drawString(str, 20 * i, 30);//缓存buf.append(str);}//将获得随机字符串,保存到session// * 获得sessionHttpSession session = request.getSession();// * 保存值session.setAttribute("number", buf.toString());//干扰线for(int i = 0 ; i < 10 ; i ++){//设置随机颜色g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));//随机画直线g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));}/** * <extension>jpg</extension>        <mime-type>image/jpeg</mime-type> *///通知浏览器发送的数据时一张图片response.setContentType("image/jpeg");//将图片发送给浏览器ImageIO.write(image, "jpg", response.getOutputStream());}





0 0