ImageServlet:
import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ImageServlet extends HttpServlet { private static final long serialVersionUID = -7529055574654373774L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage img = new BufferedImage(68, 30, 1); Graphics g = img.getGraphics(); Random r = new Random(); Color c = new Color(203, 226, 248); g.setColor(c); g.fillRect(0, 0, 68, 30); StringBuffer sb = new StringBuffer(); char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray(); int len = ch.length; for (int i = 0; i < 50; i++) { int xs = r.nextInt(68); int ys = r.nextInt(30); int xe = xs + r.nextInt(8); int ye = ys + r.nextInt(3); int red = r.nextInt(255); int green = r.nextInt(255); int blue = r.nextInt(255); g.setColor(new Color(red, green, blue)); g.drawLine(xs, ys, xe, ye); } for (int i = 0; i < 4; i++) { int index = r.nextInt(len); g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255))); if (i % 2 == 0) { g.setFont(new Font("Times New Roman", 3, 18 + r.nextInt(6))); g.drawString(String.valueOf(ch[index]), i * 15 + 3, 18); } else { g.setFont(new Font("Arial", 0, 18 + r.nextInt(6))); g.drawString(String.valueOf(ch[index]), i * 15 + 3, 28); } sb.append(ch[index]); } request.getSession().setAttribute("imageCode", sb.toString()); ImageIO.write(img, "PNG", response.getOutputStream()); } }
第一个for循环绘制50条干扰线
第二个for循环绘制4位验证码
Linux + OpenJDK 下 g.drawString 会报 Could not initialize class sun.awt.X11FontManager 异常,执行 yum install -y fontconfig 重启应用解决问题