php生成图形验证码几种方法小结

通过文字传递创建的图形按钮,详细说明请看文内英文说明 ?php Header(
“Content-type: image/gif”); // info for the browser /* PHP3 Button
generator, (c) 2000 by IzzySoft (izzysoft@buntspecht.de) * License: GPL
(and it would be nice to drop me a note that you find it * useful – if
you use it. And, of course, I am very interested in * enhancements you
made to the script! * * Purpose: generate buttons with text passed by
parameter. * * possible parameters to the script: *button- input gif
image. Just the part of the filename before the dot. *The specified
image file is expected in the same directory *as this script resides
in. *font – font to use (1 – 5; 1 is very small, 3 medium, 5 normal
size. *The script will automatically use a smaller font if text is
*too long for selected size.) Default: 5 *text – the text to be put on
the button. Will be centered. *textcolor – color for the letters.
Default: white. *in this example code only blue, white and black are
defined; *but you can add custom colors easily. *width,heigth – width
and heigth of the button. Useful only if target *button should have
different size than source image. * * Example for usage: * IMG
SRC=”button.php3?button=yellowtext=Example” * will look for yellow.gif
and put the string “Example” on it. * * I use to have three buttons I
normally generate (one displays selected * item, one is for
mouseover(), and one is the default button). The source * images are
yellow.gif, white.gif and blue.gif – so my script assumes * blue.gif as
default if “button=” not specified – you may wish to change * this
below, its easy 😉 */ // ===========================[ check fo //r
parameters and/or set defaults ]=== if (($font == “”) || ($font 5) ||
($font 1)) { $font = 5; } if ($text == “”) { $text=”Moin!”; }// button
text if ($textcolor == “”) {// color for the letters switch ($button) {
case “yellow”: case “white”: $textcolor = “black”; break; default: if
($button == “”) { $button = “blue”; } $textcolor = “white”; break; } }
// textcolor end $im_info = getimagesize(“$button.gif”); // button size
if ($width == “”) { if ($im_info == “”) { $buttonwidth = 125; } else {
$buttonwidth = “$im_info[0]”; } } else { $buttonwidth = $width; } if
($heigth == “”) { if ($im_info == “”) { $buttonheigth = 30; } else {
$buttonheigth = “$im_info[1]”; } } else { $buttonheigth = $heigth; }
$vmidth = ceil($buttonheigth / 2); //
===================================== //===[ now lets define some
colors ]=== $white = “255,255,255”; $black = “0,0,0”; $blue =
“0x2c,0c6d,0xaf”; // =====================================
//=============[ build color array ]=== // now we put the needed color
into an a //rray (if e.g. “$textcolor=white”, // the array
$textcolor_array represents //”white”) $textcolor_array = explode(“,”,
$$textcolor); // =======================[ calculate po //sition of the
text on the button ]=== do { $textwidth = strlen($text) *
imagefontwidth($font); $x = ($buttonwidth – $textwidth) / 2; $x =
ceil($x); $y = $vmidth – (imagefontheight($font) / 2); $font–; } while
(($x 0) ($font 0)); $font++; // =====================================
//======[ now we create the button ]=== if (isset($width) ||
isset($heigth)) {// size change expected? $ima =
imagecreatefromgif(“$button.gif”);// open input gif $im =
imagecreate($buttonwidth,$buttonheigth); // create img in desired size
$uglybg = ImageColorAllocate($im,0xf4,0xb2,0xe5);
ImageRectangle($im,0,0,$buttonwidth,$buttonheigth,$uglybg); $dummy =
imagecopyresized($im,$ima,0,0,0,0,$buttonwidth,$buttonheigth,$im_info[0],$im_info[1]);
if ($dummy == “”) { ImageDestroy($im); // if it didnt work, create
default below instead } else {;} ImageDestroy($ima);
ImageColorTransparent($im,$uglybg); } else { $im =
imagecreatefromgif(“$button.gif”);// open input gif } if ($im == “”) {
$im = imagecreate($buttonwidth,$buttonheigth); // if input gif not
found, $rblue = ImageColorAllocate($im, 0x2c,0x6D,0xAF);// create a
default box ImageRectangle($im,0,0,200,100,$rblue); } $color =
ImageColorAllocate($im, $textcolor_array[0], $textcolor_array[1],
$textcolor_array[2]); // allocate the color imagestring($im, $font,
$x, $y, “$text”, $color); // put the text on it ImageGif($im);// send
button to browser ImageDestroy($im);// free the used memory ?

我们先来检查一下自己的php是不是打开了gd库。
复制代码 代码如下:
if(extension_loaded(‘gd’)) {
  echo ‘你可以使用gd
‘;
  foreach(gd_info() as $cate=>$value)
    echo “$cate: $value
“;
}else
澳门新浦京娱乐游戏,  echo ‘你没有安装gd扩展’;
?>

很多人不了解PHP 可以产生非HTML的资料.这是对产生影像图非常有用的.可以从
database 产生一个简单的广告横图或更简单只产生一个图形按钮 . 我用 TTF
字型在以下的范例中 我通常取名作 button.php3:
#######################################################
—–button.php3—— ? Header(“Content-type: image/gif”);
if(!isset($s)) $s=11; $size =
imagettfbbox($s,0,”fonts/TIMES.TTF”,$text); $dx =
abs($size[2]-$size[0]); $dy = abs($size[5]-$size[3]); $xpad=9;
$ypad=9; $im = imagecreate($dx+$xpad,$dy+$ypad); $blue =
ImageColorAllocate($im, 0x2c,0x6D,0xAF); $black =
ImageColorAllocate($im, 0,0,0); $white = ImageColorAllocate($im,
255,255,255); ImageRectangle($im,0,0,$dx+$xpad-1,$dy+$ypad-1,$black);
ImageRectangle($im,0,0,$dx+$xpad,$dy+$ypad,$white); ImageTTFText($im,
$s, 0, (int)($xpad/2)+1, $dy+(int)($ypad/2), $black, “fonts/TIMES.TTF”,
$text); ImageTTFText($im, $s, 0, (int)($xpad/2), $dy+(int)($ypad/2)-1,
$white, “fonts/TIMES.TTF”, $text); ImageGif($im); ImageDestroy($im); ?
#######################################################
很重要一点是你不能在这档案中放任何HTML tags.也不能有空白行在 ?和 ? tag
之前或之後. 如果你用这段Script後看到一个不完整的影像,
表示你可能在PHP标签以外误打了字元. 以上的 script
可以由此语法在网页中叫出来: IMG SRC=”button.php3?s=36text=PHP+is+Cool”
#######################################################
—-test.php—– html head META HTTP-EQUIV=”content-type”
CONTENT=”text/html; charset=gb2312″ titleNew Page 1/title /head body IMG
SRC=”button.php3?s=36text=PHP+is+Cool” /body /html
#######################################################
test.php结果会像这样: . s 参数是设定字型大小 . 这是当 s=18 时: 注I:
字型路径 “/fonts/TIMES.TTF” 可由windows/fonts目录下取得 TIMS.TTF 字型档
Copy 至你网站的目录 fonts下即可测试 至於中文的表现 尚待各位网友提供心得
注意 我先画了一个黑色方块区再用白色位移产生 3D
效果.也陬L法在浅色背景中看出来 但你可以把背景色改为深色看看此效果.
字型也做了同样效果表现立体感. 你要先确定你的安装 PHP 时有设定支援GD 和
TTF. 可参考PHP FAQ . 我建议可以 copy libgd.a 到/usr/local/lib 和 gd*.h
相关档案到/usr/local/include 然後 make install for FreeTTF library.
可以在这~kikita/ 找到钗httf 字型哦! 注:
以下的原始码改进了上面的弁?可多行文字显示:
#######################################################
————–button.php—————– ? Header(“Content-type:
image/jpeg”); if(!isset($bgred)) $bgred=0; if(!isset($bggreen))
$bggreen=51; if(!isset($bgblue)) $bgblue=153; if(!isset($chred))
$chred=255; if(!isset($chgreen)) $chgreen=255; if(!isset($chblue))
$chblue=255; if(!isset($shadow)) $shadow=”yes”; if(!isset($wrappos))
$wrappos=20; if(!isset($crop)) $crop=2.2; if(!isset($jpegquality))
$jpegquality=80; if(!isset($s)) $s=11; $savetext=$text;
$text=wordwrap($text,$wrappos,” “,0); if (!isset($font)) $fontname=”/”;
else $fontname=”/”.$font.”.ttf”; $size =
imagettfbbox($s,0,$fontname,$text); $dx = abs($size[2]-$size[0]);
$dy = abs($size[5]-$size[3]); $upper=abs($size[5]);
$under=$size[1]; $th=$upper-$under; $xpad=9; if
(substr_count($text,chr(13))=1) { $mult=(substr_count($text,chr(13)));
$ypad=($mult*$crop*$s)+$s; } else $ypad=($crop-2)*$s; $im =
imagecreate($dx+$xpad,$th+$ypad); $color = ImageColorAllocate($im,
$bgred,$bggreen,$bgblue); $black = ImageColorAllocate($im, 0,0,0);
$fontcolor = ImageColorAllocate($im, $chred,$chgreen,$chblue);
ImageRectangle($im,0,0,$dx+$xpad-1,$th+$ypad-1,$black);
ImageRectangle($im,0,0,$dx+$xpad,$th+$ypad,$white); if ($shadow==”yes”)
ImageTTFText($im, $s, 0, (int)($xpad/2)-2+1, $th+2+(int)($ypad/2)-3,
$black, $fontname, $text); ImageTTFText($im, $s, 0, (int)($xpad/2)-2,
$th+2+(int)($ypad/2)-1-3, $fontcolor, $fontname, $text);
Imagejpeg($im,””,$jpegquality); ImageDestroy($im); ?
#######################################################
这可以下面这个 form 来产生:
#######################################################
———-test.php——————– html head titleNew Page 1/title
/head body form method=”POST” action=”button.php” p文字input type=”text”
name=”text” size=”60″/p p大小input type=”text” name=”s” size=”6″
value=”14″/p p断句的位置(wrap break position) input type=”text”
name=”wrappos” size=”3″ value=”20″/p p背景颜色/p p红色input type=”text”
name=”bgred” size=”6″ value=”0″nbsp;nbsp;nbsp; 绿色input type=”text”
name=”bggreen” size=”8″ value=”51″nbsp;nbsp;nbsp; 蓝色input type=”text”
name=”bgblue” size=”7″ value=”153″/p p字元颜色/p p红色 input type=”text”
name=”chred” size=”6″ value=”255″nbsp;nbsp;nbsp; 绿色 input type=”text”
name=”chgreen” size=”8″ value=”255″nbsp;nbsp;nbsp; 蓝色 input
type=”text” name=”chblue” size=”7″ value=”255″/p p字型 input type=”text”
name=”font” size=”20″ value=”arialbd”/p p阴影 input type=”radio”
value=”yes” checked name=”shadow”是 input type=”radio” name=”shadow”
value=”no”否/p pCrop size input type=”text” name=”crop” size=”20″
value=”2.2″/p pJpeg 品质 (0-100) input type=”text” name=”jpegquality”
size=”20″ value=”80″/p pinput type=”submit” value=”Submit” name=”B1″
input type=”reset” value=”Reset” name=”B2″/p /form /body /html
#######################################################
或是直接像上例一样呼叫:
#######################################################
—-test.php—– html head titleNew Page 1/title /head body IMG
SRC=”button.php?s=36text=PHP+is+Cool” /body /html

如果有返回信息就正确可以常用使用了
例1
复制代码 代码如下:
/**
 * vCode(m,n,x,y) m个数字  显示大小为n   边宽x   边高y
 * 自己改写记录session $code
 */
session_start();
vCode(4, 15); //4个数字,显示大小为15
function vCode($num = 4, $size = 20, $width = 0, $height = 0) {
 !$width && $width = $num * $size * 4 / 5 + 5;
 !$height && $height = $size + 10;
 // 去掉了 0 1 O l 等
 $str = “23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVW”;
 $code = ”;
 for ($i = 0; $i < $num; $i++) {
  $code .= $str[mt_rand(0, strlen($str)-1)];
 }
 // 画图像
 $im = imagecreatetruecolor($width, $height);
 // 定义要用到的颜色
 $back_color = imagecolorallocate($im, 235, 236, 237);
 $boer_color = imagecolorallocate($im, 118, 151, 199);
 $text_color = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0,
120), mt_rand(0, 120));
 // 画背景
 imagefilledrectangle($im, 0, 0, $width, $height, $back_color);
 // 画边框
 imagerectangle($im, 0, 0, $width-1, $height-1, $boer_color);
 // 画干扰线
 for($i = 0;$i < 5;$i++) {
  $font_color = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0,
255), mt_rand(0, 255));
  imagearc($im, mt_rand(- $width, $width), mt_rand(- $height,
$height), mt_rand(30, $width * 2), mt_rand(20, $height * 2),
mt_rand(0, 360), mt_rand(0, 360), $font_color);
 }
 // 画干扰点
 for($i = 0;$i < 50;$i++) {
  $font_color = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0,
255), mt_rand(0, 255));
  imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height),
$font_color);
 }
 // 画验证码
 @imagefttext($im, $size , 0, 5, $size + 3, $text_color,
‘c:WINDOWSFontssimsun.ttc’, $code);
 $_SESSION[“VerifyCode”]=$code;
 header(“Cache-Control: max-age=1, s-maxage=1, no-cache,
must-revalidate”);
 header(“Content-type: image/png;charset=gb2312”);
 imagepng($im);
 imagedestroy($im);
}
?>

例2
使用PHP,结合session和GD库扩展开发的一个生成验证码的例子(w3c推荐),可以很方便的用于项目中。而且样式美观
复制代码 代码如下:
//首先开启session
session_start();
//定义前台显示验证码长&宽
$image_width = 120;
$image_height = 40;
$characters_on_image = 6;
$font = ‘./monofont.ttf’;
//The characters that can be used in the CAPTCHA code.
//avoid confusing characters (l 1 and i for example)
$possible_letters = ‘23456789bcdfghjkmnpqrstvwxyz’;
$random_dots = 10;
$random_lines = 30;
$captcha_text_color=”0x142864″;
$captcha_noice_color = “0x142864”;
//定义要生成验证码的字符串
$code = ”;
$i = 0;
while ($i < $characters_on_image) {
$code .= substr($possible_letters, mt_rand(0,
strlen($possible_letters)-1), 1);
$i++;
}
$font_size = $image_height * 0.75;
$image = @imagecreate($image_width, $image_height);
/* setting the background, text and noise colours here */
$background_color = imagecolorallocate($image, 255, 255, 255);
$arr_text_color = hexrgb($captcha_text_color);
$text_color = imagecolorallocate($image, $arr_text_color[‘red’],
        $arr_text_color[‘green’], $arr_text_color[‘blue’]);
$arr_noice_color = hexrgb($captcha_noice_color);
$image_noise_color = imagecolorallocate($image,
$arr_noice_color[‘red’],
        $arr_noice_color[‘green’], $arr_noice_color[‘blue’]);
/* generating the dots randomly in background */
for( $i=0; $iimagefilledellipse($image, mt_rand(0,$image_width),
 mt_rand(0,$image_height), 2, 3, $image_noise_color);
}
/* generating lines randomly in background of image */
for( $i=0; $iimageline($image, mt_rand(0,$image_width),
mt_rand(0,$image_height),
 mt_rand(0,$image_width), mt_rand(0,$image_height),
$image_noise_color);
}
/* create a text box and add 6 letters code in it */
$textbox = imagettfbbox($font_size, 0, $font, $code);
$x = ($image_width – $textbox[4])/2;
$y = ($image_height – $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font ,
$code);
/* Show captcha image in the page html page */
header(‘Content-Type: image/jpeg’);// defining the image type to be
shown in browser widow
imagejpeg($image);//showing the image
imagedestroy($image);//destroying the image instance
//设置session,做验证
$_SESSION[‘6_letters_code’] = $code;
function hexrgb ($hexstr)
{
  $int = hexdec($hexstr);
  return array(“red” => 0xFF & ($int >> 0x10),
               “green” => 0xFF & ($int >> 0x8),
               “blue” => 0xFF & $int);
}

个人推荐推荐第二个生成验证码程序代码,各位同学可尝试参考对比哦,最后一个是W3C标准生成的也是利用了php
gd库。

You can leave a response, or trackback from your own site.

Leave a Reply

网站地图xml地图