//下面的行是我的 HTML 表单的元素,它呈现由下面进一步编写的 servlet 发送的图像。
<img style="margin-left:91px; margin-top:-6px;" class="image" src="http://www.abcd.com/captchaServlet">
我在 java 中使用以下代码生成验证码。
public class captchaServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
int width = 150;
int height = 50;
int charsToPrint = 6;
String elegibleChars = "ABCDEFGHJKLMPQRSTUVWXYabcdefhjkmnpqrstuvwxy1234567890";
char[] chars = elegibleChars.toCharArray();
StringBuffer finalString = new StringBuffer();
for ( int i = 0; i < charsToPrint; i++ ) {
double randomValue = Math.random();
int randomIndex = (int) Math.round(randomValue * (chars.length - 1));
char characterToShow = chars[randomIndex];
finalString.append(characterToShow);
}
System.out.println(finalString);
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedImage.createGraphics();
Font font = new Font("Georgia", Font.BOLD, 18);
g2d.setFont(font);
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHints(rh);
GradientPaint gp = new GradientPaint(0, 0,
Color.BLUE, 0, height/2, Color.black, true);
g2d.setPaint(gp);
g2d.fillRect(0, 0, width, height);
g2d.setColor(new Color(255, 255, 0));
Random r = new Random();
int index = Math.abs(r.nextInt()) % 5;
char[] data=new String(finalString).toCharArray();
String captcha = String.copyValueOf(data);
int x = 0;
int y = 0;
for (int i=0; i<data.length; i++) {
x += 10 + (Math.abs(r.nextInt()) % 15);
y = 20 + Math.abs(r.nextInt()) % 20;
g2d.drawChars(data, i, 1, x, y);
}
g2d.dispose();
response.setContentType("image/png");
OutputStream os = response.getOutputStream();
ImageIO.write(bufferedImage, "png", os);
os.close();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
但在上面的代码背景中,我猜也是使用 setPaint menthod 生成的。我希望背景是来自我的本地机器的一些图像,我应该能够提到它的 URL
URL url=this.getClass().getResource("Desktop/images.jpg");
BufferedImage bufferedImage = ImageIO.read(url);
我写上面两行只是为了让读者更好地理解问题所在。不想使用完全相同的命令。我想要的只是生成的验证码的背景应该是我选择的图像。