优快云话题挑战赛第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();
}
}