<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: Captcha code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sat, 17 May 2008 21:59:16 GMT</pubDate>
    <description>DZone Snippets: Captcha code</description>
    <item>
      <title>CaptchaImage</title>
      <link>http://snippets.dzone.com/posts/show/3976</link>
      <description>&lt;code&gt;&lt;br /&gt;    public class CaptchaImage&lt;br /&gt;    {&lt;br /&gt;        // Public properties (all read-only).&lt;br /&gt;        public string Text&lt;br /&gt;        {&lt;br /&gt;            get { return this.text; }&lt;br /&gt;        }&lt;br /&gt;        public Bitmap Image&lt;br /&gt;        {&lt;br /&gt;            get { return this.image; }&lt;br /&gt;        }&lt;br /&gt;        public int Width&lt;br /&gt;        {&lt;br /&gt;            get { return this.width; }&lt;br /&gt;        }&lt;br /&gt;        public int Height&lt;br /&gt;        {&lt;br /&gt;            get { return this.height; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Internal properties.&lt;br /&gt;        private string text;&lt;br /&gt;        private int width;&lt;br /&gt;        private int height;&lt;br /&gt;        private string familyName;&lt;br /&gt;        private Bitmap image;&lt;br /&gt;&lt;br /&gt;        // For generating random numbers.&lt;br /&gt;        private Random random = new Random();&lt;br /&gt;&lt;br /&gt;        // ====================================================================&lt;br /&gt;        // Initializes a new instance of the CaptchaImage class using the&lt;br /&gt;        // specified text, width and height.&lt;br /&gt;        // ====================================================================&lt;br /&gt;        public CaptchaImage(int length, int width, int height) : this(length, width, height, null)&lt;br /&gt;        {&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // ====================================================================&lt;br /&gt;        // Initializes a new instance of the CaptchaImage class using the&lt;br /&gt;        // specified text, width, height and font family.&lt;br /&gt;        // ====================================================================&lt;br /&gt;        public CaptchaImage(int length, int width, int height, string familyName)&lt;br /&gt;        {&lt;br /&gt;            this.text = GenerateRandomText(length);&lt;br /&gt;            this.SetDimensions(width, height);&lt;br /&gt;            this.SetFamilyName(familyName);&lt;br /&gt;            this.GenerateImage();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private string GenerateRandomText(int length)&lt;br /&gt;        {&lt;br /&gt;            Random rnd = new Random();&lt;br /&gt;            List&lt;char&gt; table = new List&lt;char&gt;();&lt;br /&gt;&lt;br /&gt;            for (char i = 'A'; i &lt;= 'Z'; i++)&lt;br /&gt;                table.Add(i);&lt;br /&gt;&lt;br /&gt;            for (char i = '0'; i &lt;= '9'; i++)&lt;br /&gt;                table.Add(i);&lt;br /&gt;&lt;br /&gt;            string retVal = "";&lt;br /&gt;            &lt;br /&gt;            for (int i = 0; i &lt; length; i++)&lt;br /&gt;                retVal += table[rnd.Next(table.Count)];&lt;br /&gt;&lt;br /&gt;            return retVal;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // ====================================================================&lt;br /&gt;        // This member overrides Object.Finalize.&lt;br /&gt;        // ====================================================================&lt;br /&gt;        ~CaptchaImage()&lt;br /&gt;        {&lt;br /&gt;            Dispose(false);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // ====================================================================&lt;br /&gt;        // Releases all resources used by this object.&lt;br /&gt;        // ====================================================================&lt;br /&gt;        public void Dispose()&lt;br /&gt;        {&lt;br /&gt;            GC.SuppressFinalize(this);&lt;br /&gt;            this.Dispose(true);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // ====================================================================&lt;br /&gt;        // Custom Dispose method to clean up unmanaged resources.&lt;br /&gt;        // ====================================================================&lt;br /&gt;        protected virtual void Dispose(bool disposing)&lt;br /&gt;        {&lt;br /&gt;            if (disposing)&lt;br /&gt;                // Dispose of the bitmap.&lt;br /&gt;                this.image.Dispose();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // ====================================================================&lt;br /&gt;        // Sets the image width and height.&lt;br /&gt;        // ====================================================================&lt;br /&gt;        private void SetDimensions(int width, int height)&lt;br /&gt;        {&lt;br /&gt;            // Check the width and height.&lt;br /&gt;            if (width &lt;= 0)&lt;br /&gt;                throw new ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.");&lt;br /&gt;            if (height &lt;= 0)&lt;br /&gt;                throw new ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.");&lt;br /&gt;            this.width = width;&lt;br /&gt;            this.height = height;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // ====================================================================&lt;br /&gt;        // Sets the font used for the image text.&lt;br /&gt;        // ====================================================================&lt;br /&gt;        private void SetFamilyName(string familyName)&lt;br /&gt;        {&lt;br /&gt;            // If the named font is not installed, default to a system font.&lt;br /&gt;            try&lt;br /&gt;            {&lt;br /&gt;                Font font = new Font(this.familyName, 12F);&lt;br /&gt;                this.familyName = familyName;&lt;br /&gt;                font.Dispose();&lt;br /&gt;            }&lt;br /&gt;            catch (Exception ex)&lt;br /&gt;            {&lt;br /&gt;                this.familyName = System.Drawing.FontFamily.GenericSerif.Name;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // ====================================================================&lt;br /&gt;        // Creates the bitmap image.&lt;br /&gt;        // ====================================================================&lt;br /&gt;        private void GenerateImage()&lt;br /&gt;        {&lt;br /&gt;            // Create a new 32-bit bitmap image.&lt;br /&gt;            Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);&lt;br /&gt;&lt;br /&gt;            // Create a graphics object for drawing.&lt;br /&gt;            Graphics g = Graphics.FromImage(bitmap);&lt;br /&gt;            g.SmoothingMode = SmoothingMode.AntiAlias;&lt;br /&gt;            Rectangle rect = new Rectangle(0, 0, this.width, this.height);&lt;br /&gt;&lt;br /&gt;            // Fill in the background.&lt;br /&gt;            HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White);&lt;br /&gt;            g.FillRectangle(hatchBrush, rect);&lt;br /&gt;&lt;br /&gt;            // Set up the text font.&lt;br /&gt;            SizeF size;&lt;br /&gt;            float fontSize = rect.Height + 1;&lt;br /&gt;            Font font;&lt;br /&gt;            // Adjust the font size until the text fits within the image.&lt;br /&gt;            do&lt;br /&gt;            {&lt;br /&gt;                fontSize--;&lt;br /&gt;                font = new Font(this.familyName, fontSize, FontStyle.Bold);&lt;br /&gt;                size = g.MeasureString(this.text, font);&lt;br /&gt;            } while (size.Width &gt; rect.Width);&lt;br /&gt;&lt;br /&gt;            // Set up the text format.&lt;br /&gt;            StringFormat format = new StringFormat();&lt;br /&gt;            format.Alignment = StringAlignment.Center;&lt;br /&gt;            format.LineAlignment = StringAlignment.Center;&lt;br /&gt;&lt;br /&gt;            // Create a path using the text and warp it randomly.&lt;br /&gt;            GraphicsPath path = new GraphicsPath();&lt;br /&gt;            path.AddString(this.text, font.FontFamily, (int)font.Style, font.Size, rect, format);&lt;br /&gt;            float v = 4F;&lt;br /&gt;            PointF[] points =&lt;br /&gt;			{&lt;br /&gt;				new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),&lt;br /&gt;				new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),&lt;br /&gt;				new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v),&lt;br /&gt;				new PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v)&lt;br /&gt;			};&lt;br /&gt;            Matrix matrix = new Matrix();&lt;br /&gt;            matrix.Translate(0F, 0F);&lt;br /&gt;            path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);&lt;br /&gt;&lt;br /&gt;            // Draw the text.&lt;br /&gt;            hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray);&lt;br /&gt;            g.FillPath(hatchBrush, path);&lt;br /&gt;&lt;br /&gt;            // Add some random noise.&lt;br /&gt;            int m = Math.Max(rect.Width, rect.Height);&lt;br /&gt;            for (int i = 0; i &lt; (int)(rect.Width * rect.Height / 30F); i++)&lt;br /&gt;            {&lt;br /&gt;                int x = this.random.Next(rect.Width);&lt;br /&gt;                int y = this.random.Next(rect.Height);&lt;br /&gt;                int w = this.random.Next(m / 50);&lt;br /&gt;                int h = this.random.Next(m / 50);&lt;br /&gt;                g.FillEllipse(hatchBrush, x, y, w, h);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            // Clean up.&lt;br /&gt;            font.Dispose();&lt;br /&gt;            hatchBrush.Dispose();&lt;br /&gt;            g.Dispose();&lt;br /&gt;&lt;br /&gt;            // Set the image.&lt;br /&gt;            this.image = bitmap;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 09 May 2007 23:18:27 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3976</guid>
      <author>mstampar (Miroslav Stampar)</author>
    </item>
    <item>
      <title>100 Line Captcha JSP</title>
      <link>http://snippets.dzone.com/posts/show/3484</link>
      <description>// description of your code here&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;100 Line Captcha JSP&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Simple, nice looking captcha implemented in 100 lines of JSP. Easily change font, colors, size, and captcha characters. Since it's a JSP you can rewrite it to do whatever the heck you want to do. Enjoy!!! ...and send me any improvements you make&lt;br /&gt;&lt;br /&gt;&lt;%@ page import="java.util.*"%&gt;&lt;br /&gt;&lt;%@ page import="java.io.*"%&gt;&lt;br /&gt;&lt;%@ page import="javax.servlet.*"%&gt;&lt;br /&gt;&lt;%@ page import="javax.servlet.http.*"%&gt;&lt;br /&gt;&lt;%@ page import="java.awt.*"%&gt;&lt;br /&gt;&lt;%@ page import="java.awt.image.*"%&gt;&lt;br /&gt;&lt;%@ page import="javax.imageio.*"%&gt;&lt;br /&gt;&lt;%@ page import="java.awt.geom.*"%&gt;&lt;br /&gt;&lt;%&lt;br /&gt; //========================================================&lt;br /&gt; // Kick Ass Captcha JSP&lt;br /&gt; //&lt;br /&gt; // Michael Connor 2007&lt;br /&gt; //&lt;br /&gt; // I just couldn't handle the thought of downloading a&lt;br /&gt; // big jar and configuring some servlet.xml and having&lt;br /&gt; // little to no control of anything...&lt;br /&gt; // You can send in height and width parameters.&lt;br /&gt; // The captcha value will be placed in the session in&lt;br /&gt; // a parameter called 'captcha'&lt;br /&gt; //&lt;br /&gt; // Feel free to use this code and do whatever the hell&lt;br /&gt; // you want to it.&lt;br /&gt; //========================================================&lt;br /&gt;&lt;br /&gt; response.setContentType("image/jpg");&lt;br /&gt;&lt;br /&gt; try {&lt;br /&gt;   &lt;br /&gt;   Color backgroundColor = Color.red;&lt;br /&gt;   Color borderColor = Color.red;&lt;br /&gt;   Color textColor = Color.white;&lt;br /&gt;   Color circleColor = new Color(160,160,160);&lt;br /&gt;   Font textFont = new Font("Arial", Font.PLAIN, 24);&lt;br /&gt;   int charsToPrint = 6;&lt;br /&gt;   int width = request.getParameter("width") != null ? Integer.parseInt(request.getParameter("width")) : 150;&lt;br /&gt;   int height = request.getParameter("height") != null ? Integer.parseInt(request.getParameter("height")) : 80;&lt;br /&gt;   int circlesToDraw = 4;&lt;br /&gt;   float horizMargin = 20.0f;&lt;br /&gt;   float imageQuality = 0.95f; // max is 1.0 (this is for jpeg)&lt;br /&gt;   double rotationRange = 0.7; // this is radians&lt;br /&gt;   BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);&lt;br /&gt;&lt;br /&gt;   Graphics2D g = (Graphics2D) bufferedImage.getGraphics();&lt;br /&gt;&lt;br /&gt;   //Draw an oval&lt;br /&gt;   g.setColor(Color.red);&lt;br /&gt;   g.fillRect(0, 0, width, height);&lt;br /&gt;&lt;br /&gt;   // lets make some noisey circles&lt;br /&gt;   g.setColor(circleColor);&lt;br /&gt;   for ( int i = 0; i &lt; circlesToDraw; i++ ) {&lt;br /&gt;     int circleRadius = (int) (Math.random() * height / 2.0);&lt;br /&gt;     int circleX = (int) (Math.random() * width - circleRadius);&lt;br /&gt;     int circleY = (int) (Math.random() * height - circleRadius);&lt;br /&gt;     g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2);&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   g.setColor(textColor);&lt;br /&gt;   g.setFont(textFont);&lt;br /&gt;&lt;br /&gt;   FontMetrics fontMetrics = g.getFontMetrics();&lt;br /&gt;   int maxAdvance = fontMetrics.getMaxAdvance();&lt;br /&gt;   int fontHeight = fontMetrics.getHeight();&lt;br /&gt;&lt;br /&gt;   // i removed 1 and l and i because there are confusing to users...&lt;br /&gt;   // Z, z, and N also get confusing when rotated&lt;br /&gt;   // 0, O, and o are also confusing...&lt;br /&gt;   // lowercase G looks a lot like a 9 so i killed it&lt;br /&gt;   // this should ideally be done for every language...&lt;br /&gt;   // i like controlling the characters though because it helps prevent confusion&lt;br /&gt;   String elegibleChars = "ABCDEFGHJKLMPQRSTUVWXYabcdefhjkmnpqrstuvwxy23456789";&lt;br /&gt;   char[] chars = elegibleChars.toCharArray();&lt;br /&gt;&lt;br /&gt;   float spaceForLetters = -horizMargin * 2 + width;&lt;br /&gt;   float spacePerChar = spaceForLetters / (charsToPrint - 1.0f);&lt;br /&gt;&lt;br /&gt;   AffineTransform transform = g.getTransform();&lt;br /&gt;&lt;br /&gt;   StringBuffer finalString = new StringBuffer();&lt;br /&gt;&lt;br /&gt;   for ( int i = 0; i &lt; charsToPrint; i++ ) {&lt;br /&gt;     double randomValue = Math.random();&lt;br /&gt;     int randomIndex = (int) Math.round(randomValue * (chars.length - 1));&lt;br /&gt;     char characterToShow = chars[randomIndex];&lt;br /&gt;     finalString.append(characterToShow);&lt;br /&gt;&lt;br /&gt;     // this is a separate canvas used for the character so that&lt;br /&gt;     // we can rotate it independently&lt;br /&gt;     int charImageWidth = maxAdvance * 2;&lt;br /&gt;     int charImageHeight = fontHeight * 2;&lt;br /&gt;     int charWidth = fontMetrics.charWidth(characterToShow);&lt;br /&gt;     int charDim = Math.max(maxAdvance, fontHeight);&lt;br /&gt;     int halfCharDim = (int) (charDim / 2);&lt;br /&gt;&lt;br /&gt;     BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB);&lt;br /&gt;     Graphics2D charGraphics = charImage.createGraphics();&lt;br /&gt;     charGraphics.translate(halfCharDim, halfCharDim);&lt;br /&gt;     double angle = (Math.random() - 0.5) * rotationRange;&lt;br /&gt;     charGraphics.transform(AffineTransform.getRotateInstance(angle));&lt;br /&gt;     charGraphics.translate(-halfCharDim,-halfCharDim);&lt;br /&gt;     charGraphics.setColor(textColor);&lt;br /&gt;     charGraphics.setFont(textFont);&lt;br /&gt;&lt;br /&gt;     int charX = (int) (0.5 * charDim - 0.5 * charWidth);&lt;br /&gt;     charGraphics.drawString("" + characterToShow, charX, &lt;br /&gt;                            (int) ((charDim - fontMetrics.getAscent()) &lt;br /&gt;                                   / 2 + fontMetrics.getAscent()));&lt;br /&gt;&lt;br /&gt;     float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;&lt;br /&gt;     int y = (int) ((height - charDim) / 2);&lt;br /&gt;//System.out.println("x=" + x + " height=" + height + " charDim=" + charDim + " y=" + y + " advance=" + maxAdvance + " fontHeight=" + fontHeight + " ascent=" + fontMetrics.getAscent());&lt;br /&gt;     g.drawImage(charImage, (int) x, y, charDim, charDim, null, null);&lt;br /&gt;&lt;br /&gt;     charGraphics.dispose();&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   //Write the image as a jpg&lt;br /&gt;   Iterator iter = ImageIO.getImageWritersByFormatName("JPG");&lt;br /&gt;   if( iter.hasNext() ) {&lt;br /&gt;     ImageWriter writer = (ImageWriter)iter.next();&lt;br /&gt;     ImageWriteParam iwp = writer.getDefaultWriteParam();&lt;br /&gt;     iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);&lt;br /&gt;     iwp.setCompressionQuality(imageQuality);&lt;br /&gt;     writer.setOutput(ImageIO.createImageOutputStream(response.getOutputStream()));&lt;br /&gt;     IIOImage imageIO = new IIOImage(bufferedImage, null, null);&lt;br /&gt;     writer.write(null, imageIO, iwp);&lt;br /&gt;   } else {&lt;br /&gt;     throw new RuntimeException("no encoder found for jsp");&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   // let's stick the final string in the session&lt;br /&gt;   request.getSession().setAttribute("captcha", finalString.toString());&lt;br /&gt;&lt;br /&gt;   g.dispose();&lt;br /&gt; } catch (IOException ioe) {&lt;br /&gt;   throw new RuntimeException("Unable to build image" , ioe);&lt;br /&gt; }&lt;br /&gt;%&gt;&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 09 Feb 2007 13:26:31 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3484</guid>
      <author>hebbar (ravindra)</author>
    </item>
  </channel>
</rss>
