【Java——生成图片验证码,并给前端浏览器返回】

CSDN话题挑战赛第2期
参赛话题:一起学Java

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

/**
 * 生成图片验证码,并给前端浏览器返回
 * 画画
 * 画笔
 * 画布
 */
@WebServlet("/validate.do")
public class ValidateServlet extends HttpServlet {
	
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//创建一个画布
		BufferedImage image=new BufferedImage(100, 30, BufferedImage.TYPE_3BYTE_BGR);
		
//		//指定画布的颜色
//		for(int i=0;i<image.getWidth();i++) {
//			for(int j=0;j<image.getHeight();j++) {
//				int color=new Random().nextInt(0xFFFFFF);
//				image.setRGB(i, j, color);
//				
//			}
//		}
		
		Graphics2D g=(Graphics2D) image.getGraphics();
		
		//设置画笔颜色
		g.setColor(new Color(
				new Random().nextInt(255),
				new Random().nextInt(255),
				new Random().nextInt(255)
				));
		
		//通过画笔来填充画布颜色
		g.fillRect(0, 0, 100, 30);
		
		//重新设置画笔颜色
		for(int i=0;i<5;i++) {
			g.setColor(new Color(
					new Random().nextInt(255),
					new Random().nextInt(255),
					new Random().nextInt(255)));
				int x1=new Random().nextInt(100);
				int y1=new Random().nextInt(30);
				int x2=new Random().nextInt(100);
				int y2=new Random().nextInt(30);
				g.drawLine(x1, y1, x2, y2);
		}
		
		//重新设置字体字形字号
		Font font=new Font("楷体",Font.BOLD,25);
		
		g.setFont(font);
		
		String content="LOVE";
		int x=15;
		int y=20;
		for(int i=0;i<content.length();i++) {
			char c=content.charAt(i);
			//随机生成0-60°之间角度
			int degree=new Random().nextInt(120)-60;
			//设置旋转
			g.rotate(Math.PI/180*degree,x,y);
			g.drawString(c+"", x, y);
			g.rotate(-Math.PI/180*degree,x,y);
			x+=20;
		}
		
		//响应数据类型
		response.setContentType("image/png");
		//获取字节流
		OutputStream out =response.getOutputStream();
		//将image图片中数据以png格式进行压缩
		//并写到out输出流中
		ImageIO.write(image, "png", out);
		out.close();
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

God Zhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值