//下面的行是我的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=this.getClass().getResource("Desktop/images.jpg");
BufferedImage bufferedImage = ImageIO.read(url);
我只是写上面两行,让读者更好地理解问题所在。不想使用完全相同的命令。我想要的只是生成的验证码代码的背景应该是我选择的图像。
答案 0 :(得分:2)
而不是打电话
g2d.setPaint(gp);
g2d.fillRect(0, 0, width, height);
您可能需要拨打以下内容:
g2d.drawImage(bufferedImage, 0, 0, null);