2008/11/03

php生成扭曲变形的验证码

效果:
原理:通过数学函数对图像的点重新分布,得到扭曲效果。首先生成一副正常的图片,然后遍历每个点,取得其rgb色和坐标,通过数学函数变换点的坐标值,然后在写入到新的图像中,这样即得到扭曲的图形。要得到更复杂的图形,可以把每个字符当做一副图片,使用不同的字体,变形后再写入新的图像,就可以得到像google那样扭扭曲曲的验证码了。
 
line18:中"ROOT.'/app/vendors/MSYHBD.TTF'"为字体文件路径,修改指向某个字体文件即可。
 
代码如下,在项目中可以使用,单独拿出来未测试:
 
01 <?php
02 /**
03 * 取得验证码图像
04 *
05 * @param string $string 字符
06 * @param int $im_x
07 * @param int $im_y
08 */
09 function getAuthImage( $string , $im_x = 120 , $im_y = 60) {
10         ob_start();
11         $im_x = 120;
12         $im_y = 60;
13
14         $im = imagecreatetruecolor ($im_x, $im_y);
15         imagefill($im, 0, 0, imagecolorallocate($im,255,255,255) );
16
17         $stringColor = imagecolorallocate($im, 17, 158, 20);
18         imagettftext ($im, 24, rand(-6 , 6), $im_x*0.1, $im_y*0.7, $stringColor, ROOT.'/app/vendors/MSYHBD.TTF', $string);
19        
20         //扭曲,变形
21         $distortion_im = imagecreatetruecolor ($im_x*1.5 , $im_y);       
22         imagefill($distortion_im, 0, 0, imagecolorallocate($distortion_im,255,255,255) );
23         for ( $i=0; $i<$im_x; $i++) {
24             for ( $j=0; $j<$im_y; $j++) {
25                 $rgb = imagecolorat($im, $i , $j);
26                 if( (int)($i+20+sin($j/$im_y*2*M_PI)*10) <= imagesx($distortion_im) && (int)($i+20+sin($j/$im_y*2*M_PI)*10) >=0 ) {
27                     imagesetpixel ($distortion_im, (int)($i+20+sin($j/$im_y*2*M_PI-M_PI*0.4)*8) , $j , $rgb);
28                 }
29             }
30         }
31        
32         //imageline
33         for($i=0; $i <= 1; $i++) {
34             $linecolor = imagecolorallocate($distortion_im, 17, 158, 20);
35             $lefty = rand(1, $im_y-1);
36             $righty = rand(1, $im_y-1);
37             imageline($distortion_im, 0, $lefty, imagesx($distortion_im), $righty, $linecolor);
38         }
39         //pixel
40         for($i=0; $i <= 64; $i++) {
41             $pointcolor = imagecolorallocate($distortion_im, 17, 158, 20);
42             imagesetpixel($distortion_im, rand(0, imagesx($distortion_im)), rand(0, imagesy($distortion_im)), $pointcolor);
43         }
44         //边框
45         //imagerectangle($distortion_im, 0, 0, imagesx($distortion_im)-1, imagesy($distortion_im)-1, imagecolorallocate($distortion_im, 17, 158, 20) );
46
47         ob_clean();
48         header('Content-type: image/jpeg');
49         imagejpeg ($distortion_im);
50         imagedestroy($im);
51         imagedestroy($distortion_im);
52 }
53 ?>
---
 

没有评论:

发表评论