欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php gd实现简单图片验证码与图片背景文字水印

程序员文章站 2022-05-03 22:01:02
1、让水印文字铺满图片: 大致效果: 代码: 2、简单验证码效果: 代码: ......

1、让水印文字铺满图片:

大致效果:

php gd实现简单图片验证码与图片背景文字水印

代码:

<?php
function appendspreadtextmark($imagedir, $marktext)
{
    $fontfile = "simsun.ttf";
    $info = getimagesize($imagedir);
    $imwidth = $info[0];
    $imheight = $info[1];
    $type = $info[2];//1 = gif,2 = jpg,3 = png,4 = swf,5 = psd,6 = bmp,7 = tiff(intel byte order),8 = tiff(motorola byte order),9 = jpc,10 = jp2,11 = jpx,12 = jb2,13 = swc,14 = iff,15 = wbmp,16 = xbm
    $ext = image_type_to_extension($type, false);
    $mime = $info['mime'];
    
    $imgcrefunc = "imagecreatefrom".$ext;
    $imgres = $imgcrefunc($imagedir);
    
    $picrangelimit = $imheight > $imwidth ? $imwidth : $imheight;
    $fintsize = (int)($picrangelimit / 50);
    if ($fintsize < 5) {
        $fintsize = 5;
    }
   
    $textcolor = imagecolorallocatealpha($imgres, 0, 0, 0, 100);

    $charcount = mb_strlen($marktext, 'utf-8');
    $steplengthx = $fintsize * 4;
    $steplengthy = (int)($fintsize * $charcount * 1.2);
    $numx = (int)($imwidth / $steplengthx) + 1;
    $numy = (int)($imheight / $steplengthy) + 1;
    $pointleft = 0;
    $pointbottom = $steplengthy;
    for ($iny = 0; $iny < $numy; $iny ++) {
        $pointleft = 0;
        for ($inx = 1; $inx < $numx; $inx ++) {
            imagettftext($imgres, $fintsize, 45, $pointleft, $pointbottom, $textcolor, $fontfile, $marktext);
            $pointleft += $steplengthx;
        }
        $pointbottom += $steplengthy;
    }
    
    
    header('content-type:' . $mime);
    $imgrespfunc = 'image' . $ext;
    $imgrespfunc($imgres);
    imagedestroy($imgres);
}

$imagedir = "pic.jpg";
$marktext = "水印内容";
appendspreadtextmark($imagedir, $marktext);

 

2、简单验证码效果:

php gd实现简单图片验证码与图片背景文字水印

代码:

<?php
//创图像
$im = @imagecreatetruecolor(500, 150) or die("cannot initialize new gd image stream");
//分配颜色
$backgroundcolor = imagecolorallocate($im, 0, 0, 0);//第一个分配的颜色默认为背景
$textcolor = imagecolorallocate($im, 0, 0, 255);
//画像素点
for ($i=0; $i<500; $i++)
{
    imagesetpixel($im, rand(0, 500), rand(0,150), $textcolor);
}
$textstr = '$im = @imagecreatetruecolor(100, 50)';
//写字符串(原图像、字体、x坐标、y坐标、待写字符串、字符串颜色)
imagestring($im, 4, 10, 10,  $textstr, $textcolor);

$textstr = '$backgroundcolor = imagecolorallocate($im, 0, 0, 0)';
imagestring($im, 4, 10, 30,  $textstr, $textcolor);

$textstr = '$textcolor = imagecolorallocate($im, 0, 0, 255)';
imagestring($im, 4, 10, 50,  $textstr, $textcolor);  

$textstr = 'imagestring($im, 5, 10, 10,  $textstr, $textcolor)';
imagestring($im, 4, 10, 70,  $textstr, $textcolor);  



header("content-type: image/png");
imagepng($im);
imagedestroy($im);