开发者社区> 问答> 正文

java生成汉字验证码的时候显示不正常? 400 报错

java生成汉字验证码的时候显示不正常? 400 报错

在session看是正确 的,有四个汉字,但是显示在图片上只有第二个字显示,不知道出错在哪里

下面是代码:

@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		int width = 166;
		int height = 45; 
		resp.setHeader("Pragma", "No-cache");
		resp.setHeader("Cache-Control", "No-cache");
		resp.setDateHeader("Expires", 0);
		
		resp.setContentType("image/jpeg");
		
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		Graphics g = image.getGraphics();
		Random random = new Random();
		Font font = new Font("宋体", Font.ITALIC, 22);
		g.fillRect(0, 0, width, height);
		g.setFont(font);
		
		String sRand = "";
		String ctmp = "";
		int itmp = 0;
		for(int i = 0; i < 4; i++){
			String[] rBase= {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
			int r1 = random.nextInt(3) + 11;
			String str_r1 = rBase[r1];
			int r2;
			
			if(r1 == 13){
				r2 = random.nextInt(7);
			}else{
				r2 = random.nextInt(16);
			}
			
			String str_r2 = rBase[r2];
			int r3 = random.nextInt(6) + 10;
			
			String str_r3 = rBase[r3];
			
			int r4 ;
			if(r3 == 10){
				r4 = random.nextInt(15) + 1;
			}else if(r3 == 15){
				r4 = random.nextInt(15);
			}else{
				r4 = random.nextInt(16);
			}
			
			String str_r4 = rBase[r4];
			
			byte[] bytes = new byte[2];
			String str_r12 = str_r1 + str_r2;
			
			int tempLow = Integer.parseInt(str_r12,16);
			bytes[0] = (byte) tempLow;
			
			String str_r34 = str_r3 + str_r4;
			
			int tempHigh = Integer.parseInt(str_r34, 16);
			bytes[1] = (byte) tempHigh;
			
			ctmp = new String(bytes);
			sRand += ctmp;
			Color color = new Color(20 + random.nextInt(110));
			g.setColor(color);
			g.drawString(ctmp, width/6*i+23, height/3);
			
			HttpSession session = req.getSession(true);
			session.setAttribute("randCheckCode", sRand);
			g.dispose();
			ImageIO.write(image, "JPEG", resp.getOutputStream());
		
	}

		
	}

下面是显示结果:

    

 

    

展开
收起
爱吃鱼的程序员 2020-05-30 21:32:37 550 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    g.drawString(ctmp, width/6*i+23, 30)######还是不对

    2020-05-30 21:32:37
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载