2010-08-10 80 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