2010-08-10 55 views
-1

我正在为我的网站编写一个fastcgi应用程序C.在GD验证码生成器C

如何使用GD生成验证码图像?

我在谷歌搜索了一些东西(仍然搜索正在进行),但如果有人能够给我关于该程序的基本想法,这将是很好的。

对于随机数字,我将使用纳秒作为种子(或使用它本身)。

在此先感谢。

回答

2

看那void gdImageStringUp(gdImagePtr im, gdFontPtr font, int x, int y, unsigned char *s, int color) (FUNCTION)代码示例(你几乎可以复制粘贴)..

#include "gd.h" 
    #include "gdfontl.h" 
    #include <string.h> 

    /*... inside a function ...*/ 
    gdImagePtr im; 
    int black; 
    int white; 
    /* String to draw. */ 
    char *s = "Hello."; 
    im = gdImageCreate(100, 100); 
    /* Background color (first allocated) */ 
    black = gdImageColorAllocate(im, 0, 0, 0); 
    /* Allocate the color white (red, green and blue all maximum). */ 
    white = gdImageColorAllocate(im, 255, 255, 255); 
    /* Draw a centered string going upwards. Axes are reversed, 
    and Y axis is decreasing as the string is drawn. */ 
    gdImageStringUp(im, gdFontGetLarge(), 
    im->w/2 - gdFontGetLarge()->h/2, 
    im->h/2 + (strlen(s) * gdFontGetLarge()->w/2), s, white); 
    /* ... Do something with the image, such as 
    saving it to a file... */ 
    /* Destroy it */ 
    gdImageDestroy(im); 

http://www.libgd.org/Font

噪声与随机进行像素/线/等等,这很简单:

/*... inside a function ...*/ 
    gdImagePtr im; 
    int black; 
    int white; 
    im = gdImageCreate(100, 100); 
    /* Background color (first allocated) */ 
    black = gdImageColorAllocate(im, 0, 0, 0); 
    /* Allocate the color white (red, green and blue all maximum). */ 
    white = gdImageColorAllocate(im, 255, 255, 255); 
    /* Set a pixel near the center. */ 
    gdImageSetPixel(im, 50, 50, white); 
    /* ... Do something with the image, such as 
    saving it to a file... */ 
    /* Destroy it */ 
    gdImageDestroy(im); 

http://www.libgd.org/Drawing

LibGD有像他们的网站上的亿万个例子。

1

我不知道GD是什么,但我假设它是某种图像库的,但我可以给你实现整个验证码事的想法:

  1. 你添加<img>标签链接到您的CGI应用程序并发送一个“种子”参数。由于第二步,你从PHP代码中记下你的种子。
  2. 您在表单中添加隐藏字段,该字段包含步骤1中的种子。它必须相同。
  3. 在你链接到你的表单的php文件中,你有一个从种子生成验证码的函数。 这是复制在你的C文件!
  4. 在您的cgi文件中,您使用上面生成的验证码并在图像上绘制数字,应用一些随机变换(小的东西,例如像素移动2-3像素左右,绘制线条等),然后返回图像数据。
  5. 在php文件中,表单重定向到您从隐藏字段中重新生成值,该字段包含种子并测试用户输入的内容。

至于从种子验证码生成器,这样的事情应该足够了:

static int seed; // write to this when you get the value 
int nextDigit() 
{ 
    seed=seed*32423+235235; 
    seed^=0xc3421d; 
    return seed%10; // %26 if you want letters, %36 if you want letters+numbers 
} 

int captcha() 
{ 
    return nextDigit()+nextDigit()*10+nextDigit()*100+ 
    nextDigit()*100+nextDigit()*10; 
} 
+0

最有可能我会使用数字验证码,但你的代码是值得一试。 :) 谢谢。 – Nilesh 2010-08-10 13:04:09