Erlo

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

时间:2019-08-04 21:03   阅读:78次   来源:博客园页面报错

点赞

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

大致效果:

代码:

<?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
//创图像
$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);

 

下一篇:Ubuntu中实现Docker内安装jenkins+je...

评论留言

还没有评论留言,赶紧来抢楼吧~~

Erlo大厅()

* 这里是“吐槽厅”,所有人可看,只保留当天信息。

  • Erlo.vip2019-09-21 19:49:44Hello、欢迎使用吐槽厅,这里是个吐槽的地方。
  • 首页 笔记分享 案例展示 ERLO 搜索
    鼠标试试
    返回顶部