JSP Forum Image Protection
You've grown to hate them, and yet everybody has them. We are talking about the protection images you see when you go to create a new user account on forums, or post an email on a website. The reason of course is so that we the web hosts can protect ourselves from the scourge of the internet, the blasted spammers and hackers. I have seen many versions of this code in PHP, but never anything in JSP/Servlets. Here is a first attempt at code that would produce output a decent output.
In order to use the JSP, you would have to set the session attribute "_code" to the code that you want produced, before the reference to jsp can be called in an image. An example of that would be in the webpage that calls contains the <img src="xxx.jsp"/>, it should do
<% session.setAttribute("_code","UNIQUECODE");%>
protectionimage.jsp
<%@ page import="java.io.File,java.awt.*,
java.awt.image.BufferedImage,
java.awt.font.FontRenderContext,
javax.imageio.ImageIO,java.io.OutputStream"%><%
String code = "";
if(session.getAttribute("_code") != null) {
code = (String) session.getAttribute("_code");
}
int size = 20;
Color background = Color.white;
Font font = new Font("Serif", Font.BOLD, (int) size);
int width = 200;
int height = 75;
BufferedImage buffer =
new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = buffer.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
FontRenderContext fc = g2.getFontRenderContext();
buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
g2 = buffer.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(font);
g2.setColor(background);
g2.fillRect(0,0,width,height);
for (int i = 0; i < 50; i++) {
g2.setColor(new Color((float) (0.2f + (Math.random()*0.7)),
(float) (0.2f + (Math.random()*0.7)),
(float) (0.2f + (Math.random()*0.7))
)
);
g2.fillOval((int) (Math.random() * width),
(int) (Math.random() * height),
(int) (Math.random() * 20),
(int) (Math.random() * 20)
);
}
for (int i = 0; i < 200; i++) {
g2.setColor(new Color((float) (0.2f + (Math.random()*0.7)),
(float) (0.2f + (Math.random()*0.7)),
(float) (0.2f + (Math.random()*0.7))
)
);
g2.drawLine((int) (Math.random() * 2 * width)-width,
(int) (Math.random() * 2 * height)-height,
(int) (Math.random() * 2 * width)-width,
(int) (Math.random() * 2 * height)-height
);
}
float window = (width-size) * 1.0f / code.length();
for (int i = 0; i < code.length(); i++) {
int x = size/2 + (int) (i * (window) + Math.random() * (window-size));
int y = size + (int) ((height-size) * Math.random());
g2.setColor(new Color((float) (Math.random()*0.3),
(float) (Math.random()*0.3),
(float) (Math.random()*0.3)
)
);
g2.drawString(code.substring(i,i+1),x,y);
}
response.setContentType("image/png");
OutputStream os = response.getOutputStream();
ImageIO.write(buffer, "png", os);
os.close();
%>





