gpt4 book ai didi

java - servlet 中背景的路径

转载 作者:行者123 更新时间:2023-11-30 09:30:03 25 4
gpt4 key购买 nike

enter image description here

//下面一行是我的 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 方法生成的。我希望背景是我本地机器上的一些图像 whoz URL 我应该可以像这样提到

URL url=this.getClass().getResource("Desktop/images.jpg");
BufferedImage bufferedImage = ImageIO.read(url);

我写以上两行只是为了让读者更好地理解问题所在。不想使用完全相同的命令。我想要的只是生成的验证码背景应该是我选择的图像。

最佳答案

而不是调用

g2d.setPaint(gp);
g2d.fillRect(0, 0, width, height);

你可能需要这样调用:

g2d.drawImage(bufferedImage, 0, 0, null);

关于java - servlet 中背景的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13437043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com