阿里云新用户优惠

第八章 图形图像处理

一、GD库的使用

1、GD库是什么

  PHP 除了可以处理文本数据外,通过一个叫 GD 的 PHP 扩展库,PHP 还可以动态生成不同格式图像或者对已有图片进行加工处理。
  GD 库是一个开源的用于创建图形图像的函数库,该函数库由C语言编写,可以在 Perl、PHP 等多种语言中调试运用。PHP 使用 GD 库可以制作出各类丰富的图形图像效果,如统计图,为图片添加水印以及生成动态图表等。

2、加载GD库

  在php.ini文件,找到选项“;extension=php_gd2.dll”,将之前的分号删除,重新启动Apache服务器后,就可以使用GD2函数库了。目前PHP已将GD2函数库作为默认的扩展。

  • 可以通过 phpinfo() 函数来获取 GD2 函数库的安装信息,验证 GD 库是否安装成功。
  • 还可以通过打印 gd_info() 函数来验证 GD 库是否安装成功,如下所示:
<?php
    phpinfo();
    print_r(gd_info());
?>

二、常见的图像处理

  在PHP程序中处理图像的操作主要分为以下4个步骤:

  • 创建画布。
  • 在画布上绘制图形或输入文本。
  • 保存并输出图形。
  • 销毁图像资源。

1、创建背景图片

  通常使用 imagecreate() 和 imagecreatetruecolor() 来创建指定的画布,它们的语法格式如下所示: imagecreate(int $width, int $height) — 创建一幅大小为 x和 y的图像(默认没有颜色,需要指定颜色) imagecreatetruecolor(int $width, int $height)— 创建一幅大小为 x和 y的图像(默认为黑色)

  • 都是创建一幅大小为 x和 y的图像
  • imagecreate默认没有颜色,需要指定颜色
  • imagecreatetruecolor默认为黑色,设置颜色后需要填充
<?php
    header ('Content-Type: image/png');
    $im  = imagecreate(100, 50) or die("画布1创建失败!");
    $img = imagecreatetruecolor(120, 20) or die('画布2创建失败!');

    //区别
    $im = imagecreate(100, 100);
    // $im = imagecreatetruecolor(100, 100);
    // 将背景设为红色
    $red = imagecolorallocate($im, 255, 0, 0);
    // imagefill($im, 0, 0, $red);

    header('Content-type: image/png');
    imagepng($im);
    imagedestroy($im);
?>

  由于没有在画布上执行任何操作,所以浏览器不会输出画布。但是可以通过 imagesx() 和 imagesy() 来获取图像的宽和高(单位是像素),它们的语法格式如下所示:
imagesx(resource $image)
imagesy(resource $image)

<?php
    $img = imagecreatetruecolor(120, 20) or die('画布创建失败!');
    echo '画布的宽度为:'.imagesx($img).'像素';
    echo '<br>画布的高度为:'.imagesy($img).'像素';
?>

2、使用已有图片创建新图形

函数 描述
imagecreatefromgif() 通过 GIF 文件或者 URL 新建一个图像
imagecreatefromjpeg() 通过 JPEG 文件或者 UR 新建一个图像
imagecreatefrompng() 通过 PNG 文件或者 UR L新建一个图像
imagecreatefromwbmp() 通过 WBMP 文件或者URL,新建一个图像

3、输出图片

函数 描述
imagegif() 输出一个GIF格式图像到浏览器或文件
imagejpeg() 输出一个JPEG格式图像到浏览器或文件
imagepng() 输出一个PNG格式图像到浏览器或文件

语法格式如下所示:
imagegif(resource $image[, string $filename])
imagejpeg(resource $image[, string $filename[, int $quality]])
imagepng(resource $image[, string $filename])

  • 其中,$image 为创建的图像资源;
  • $filename 为可选参数,用来设置文件的保存路径,如果设置为 NULL,则将会直接输出原始图像流;
  • $quality 为可选参数,用来设置输出图片的质量,范围从 0(最差质量,文件更小)到 100(最佳质量,文件最大)。默认为 75。
<?php
    header('Content-type:image/png');
    // header('Content-type:image/jpeg');
    $image1 = imagecreatefrompng('https://xiyoudaodao.gitee.io/css/images/logo.png');
    //输出到文件
    imagepng($image1,'php.png');
    //输出到页面
    imagepng($image1);
?>

  生成的图像要输出到浏览器上,还需要在PHP程序中发送标头信息来设置MIME文件类型,针对GIF、JPEG、PNG图像分别使用的标头信息文件信息如下:
header("Content-type: image/gif")
header("Content-type: image/jpeg")
header("Content-type: image/png")

4、销毁图像资源

  PHP程序处理图像的最后一个环节就是销毁图像。所谓销毁图像就是释放内存与指定图像的存储单元,可以通过imagedestroy()函数来完成。
该函数的语法格式如下:

  • imagedestroy(resource $image)
    • 其中参数$image是由图像创建函数返回的图像标识符。
<?php
    header('Content-type:image/png');
    $image = imagecreatefrompng('https://xiyoudaodao.gitee.io/css/images/logo.png');
    imagepng($image);
    imagedestroy($image);
?>

5、设置颜色

  画布创建完成后,还设置图像的颜色。在 PHP 中提供了 imagecolorallocate() 和 imagecolorallocatealpha() 两个函数来设置图像的颜色。

① imagecolorallocate() 函数
  • imagecolorallocate(resource $image, int $red, int $green, int $blue)
    • $image 为要设置颜色的图像资源,imagecolorallocate() 函数会返回一个标识符,代表了由给定的 RGB 成分组成的颜色;
    • $red,$green 和 $blue 分别是所需要的颜色的红,绿,蓝成分,取值范围是 0 到 255 的整数或者十六进制的 0x00 到 0xFF。
<?php
    $image = imagecreate(100, 100);
    $blue = imagecolorallocate($image, 0, 0, 255);
    $red = imagecolorallocate($image, 255, 0, 0);
    $green = imagecolorallocate($image, 0, 255, 0);
    header('Content-type:image/jpeg');
    imagejpeg($image);
    imagedestroy($image);
?>

提示:如果是使用 imagecreate() 函数创建的图像资源,在第一次调用 imagecolorallocate() 函数时会默认为其填充背景色。

② imagecolorallocatealpha() 函数

  imagecolorallocatealpha() 函数的作用和 imagecolorallocate() 相同,但多了一个额外的设置透明度的参数 alpha,函数的语法格式如下:

  • imagecolorallocatealpha(resource $image, int $red, int $green, int $blue, int $alpha)
    • $image 为要设置颜色的图像资源;
    • $red,$green 和 $blue 分别是所需要的颜色的红,绿,蓝成分,取值范围是 0 到 255 的整数或者十六进制的 0x00 到 0xFF;
    • $alpha 用来设置颜色的透明的,取值范围在 0 到 127 之间,0 表示完全不透明,127 则表示完全透明。
<?php
    $size=300;
    $image=imagecreatetruecolor($size,$size);
    //用白色背景加黑色边框画个方框
    $white=imagecolorallocate($image,255,255,255);
    $border=imagecolorallocate($image,0,0,0);
    imagefilledrectangle($image,0,0,$size-1,$size-1,$white);
    imagerectangle($image,0,0,$size-1,$size-1,$border);
    $yellow_x=100;
    $yellow_y=75;
    $red_x=120;
    $red_y=165;
    $blue_x=187;
    $blue_y=125;
    $radius=150;
    //用alpha值分配一些颜色
    $yellow=imagecolorallocatealpha($image,255,255,0,75);
    $red=imagecolorallocatealpha($image,255,0,0,75);
    $blue=imagecolorallocatealpha($image,0,0,255,75);
    //画3个交迭的圆
    imagefilledellipse($image,$yellow_x,$yellow_y,$radius,$radius,$yellow);
    imagefilledellipse($image,$red_x,$red_y,$radius,$radius,$red);
    imagefilledellipse($image,$blue_x,$blue_y,$radius,$radius,$blue);
    //不要忘记输出正确的header!
    header('Content-type:image/png');
    //最后输出结果
    imagepng($image);
    imagedestroy($image);
?>

6、绘制图形

  在PHP中绘制图形是函数非常丰富,包括点、线、文本文字、颜色块以及各种几何图形等可以想象出来的平面图形,都可以通过PHP中提供的各种画图函数完成。 另外,这些图形绘制函数都需要使用画布资源,并在画布中的位置通过坐标(原点是该画布的左上角的起始位置,以像素为单位,沿着X轴正方向向右延伸,Y轴正方向向下延伸)决定,而且还可以通过函数中最后一个参数,设置每个图形的颜色。

① 区域填充

  区域填充不可以用来绘制图像,但它可以将一个已存在图像的颜色替换为其它颜色。在 PHP 中通过 imagefill() 函数来执行区域填充,它的语法格式如下所示:

  • imagefill(resource $image, int $x, int $y, int $color)
    • $image 为创建的图像资源;$x 和 $y 为要设置颜色的横纵坐标
    • $color 为要设置的颜色
    • 会将与坐标(x,y)颜色相同且相邻的点的颜色替换为 $color 设置的颜色
<?php
    $im = imagecreatetruecolor(100, 100);
    // 将背景设为红色
    $red = imagecolorallocate($im, 255, 0, 0);
    imagefill($im, 0, 0, $red);

    header('Content-type: image/png');
    imagepng($im);
    imagedestroy($im);

    // 图片
    header('Content-type:image/png');
    $img = imagecreatefrompng('https://xiyoudaodao.gitee.io/css/images/logo.png');
    $blue = imagecolorallocate($img, 0, 0, 255);
    imagefill($img, 5, 5, $blue);
    imagepng($img);
    imagedestroy($img);
?>
② 绘制点和线

在PHP程序中绘制点,可以通过函数imagesetpixel()来完成。该函数的语法格式如下:

  • imagesetpixel(resource $image, int $x, int $y, int $color)
    • 在$image图像上用颜色$color在坐标(x,y)上绘制一个点。

在PHP程序中绘制直线,可以通过函数imageline()来完成。该函数的语法格式如下:

  • imageline(resource $image, int $x1, int $y1, int $x2, int $y2, int $color)
    • 在$image图像上用颜色$color从坐标($x1,$y1)到($x2,$y2)上绘制一条直线。
<?php
    $img = imagecreate(200, 100);
    imagecolorallocate($img, 255, 255, 255);
    $blue = imagecolorallocate($img, 0, 0, 255);
    $red = imagecolorallocate($img, 255, 0, 0);
    for ($i=0; $i <= 50; $i++) {
        $color = imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255));
        imagesetpixel($img, rand(0, 200), rand(0, 100), $color);
        imageline($img, rand(0, 200), rand(0, 100), rand(0, 200), rand(0, 100), $color);
    }
    header('Content-type:image/jpeg');
    imagejpeg($img);
    imagedestroy($img);
?>
③ 绘制矩形

  在 PHP 中我们可以使用 imagerectangle() 或者 imagefilledrectangle() 函数来绘制一个矩形,与 imagerectangle() 函数不同的是 imagefilledrectangle() 函数会在绘制完成矩形后填充矩形,它们的语法格式如下所示:
imagerectangle(resource $image, int $x1, int $y1, int $x2, int $y2, int $color)
imagefilledrectangle(resource $image, int $x1, int $y1, int $x2, int $y2, int $color)
这两个函数的功能类似,都是在 $image 画布中画一个矩形,矩形的左上角坐标为($x1,$y1),右下角坐标为($x2,$y2),不同的是 imagerectangle() 是使用 $color 参数指定矩形的边线颜色,而 imagefilledrectangle() 则是使用这个颜色填充矩形。

<?php
    $img = imagecreate(300, 150);
    imagecolorallocate($img, 255, 255, 255);
    $blue = imagecolorallocate($img, 0, 0, 255);
    $red = imagecolorallocate($img, 255, 0, 0);
    imagerectangle($img, 5, 5, 145, 145, $blue);
    imagefilledrectangle($img, 150, 5, 295, 145, $red);
    header('Content-type:image/jpeg');
    imagejpeg($img);
    imagedestroy($img);
?>
④ 绘制多边形

  在 PHP 中可以使用 imagepolygon() 函数来绘制一个多边形;也可以使用 imagefilledpolygon() 来绘制并填充一个多边形,它们的语法格式如下所示:

  • imagepolygon(resource $image, array $points, int $num_points, int $color)
  • imagefilledpolygon(resource $image, array $points, int $num_points, int $color)
    • 这两个函数都是可以在画布 $image 中画一个多边形;
    • $points 是一个数组,包含了多边形的各个顶点坐标,例如 $points[0]=x0,$points[1]=y0,$points[2]=x1,$points[3]=y1,依此类推;
    • $num_points 用来设置多边形的顶点数,必须大于 3;
    • imagepolygon() 函数会使用 $color 颜色来指定多边形边线的颜色,而 imagefilledpolygon() 则是使用 $color 来填充多边形。
    • $points 数组中的顶点坐标数(坐标是成对出现的)不得小于多边形的顶点数 $num_points。
<?php
    $img = imagecreate(300, 150);
    imagecolorallocate($img, 255, 255, 255);
    $blue = imagecolorallocate($img, 0, 0, 255);
    $red = imagecolorallocate($img, 255, 0, 0);
    $points1 = array(
        155,35,
        250,15,
        295,56,
        233,115,
        185,77
    );
    $points2 = array(
        5,5,
        100,15,
        140,66,
        70,135,
        25,77
    );
    imagepolygon($img, $points1, rand(3, 5), $red);
    imagefilledpolygon($img, $points2, rand(3, 5), $blue);
    header('Content-type:image/jpeg');
    imagejpeg($img);
    imagedestroy($img);
?>
⑤ 绘制椭圆

  在 PHP 中可以使用 imageellipse() 函数来绘制一个椭圆,或者使用 imagefilledellipse() 函数绘制并填充一个椭圆,它们的语法如下所示:

  • imageellipse(resource $image, int $cx, int $cy, int $width, int $height, int $color)
  • imagefilledellipse(resource $image, int $cx, int $cy, int $width, int $height, int $color)
    • 这两个函数都可以在画布 $image 上绘制一个椭圆,其中 $cx 和 $cy 分别代表椭圆圆心的横纵坐标;
    • $width 和 $height 分别代表椭圆的宽度和高度;
    • $color,imageellipse() 用来指定椭圆边线的颜色,而 imagefilledellipse() 则用 $color 颜色来填充椭圆。
<?php
    $img = imagecreate(300, 150);
    imagecolorallocate($img, 255, 255, 255);
    $blue = imagecolorallocate($img, 0, 0, 255);
    $red = imagecolorallocate($img, 255, 0, 0);
    imageellipse($img, 75, 75, 80, 120, $red);
    imagefilledellipse($img, 225, 75, 100, 120, $blue);
    header('Content-type:image/jpeg');
    imagejpeg($img);
    imagedestroy($img);
?>
⑥ 绘制弧线

  在 PHP 中可以使用 imagearc() 函数来画出一条弧线或者圆形,也可以使用 imagefilledarc() 函数来绘制弧线或者圆形并填充,它们的语法格式如下所示:

  • imagearc(resource $image, int $cx, int $cy, int $width, int $height, int $start, int $end, int $color)
  • imagefilledarc(resource $image, int $cx, int $cy, int $width, int $height, int $start, int $end, int $color, int $style)
    • 这两个函数都可以在画布 $image 上绘制一个椭圆弧,其中 $cx 和 $cy 分别为圆弧中心点的横纵坐标;
    • $width 和 $height 分别为圆弧的宽度和高度;
    • $start 和 $end 分别代表圆弧的起点角度和终点角度,0° 为钟表 3 点钟的位置,以顺时针方向递增;
    • $color 参数,imagearc() 用来表示圆弧的线条颜色,而 imagefilledarc() 用来表示弧线区域的填充色;
    • imagefilledarc() 函数比 imagearc() 函数多了一个 $style 参数,它用来设置颜色的填充类型,可以是如下的值:
      • IMG_ARC_PIE:普通填充,产生圆形边界;
      • IMG_ARC_CHORD:只使用直线连接起点和终点,与 IMG_ARC_PIE 互斥;
      • IMG_ARC_NOFILL:指明弧或弦只有轮廓,不填充;
      • IMG_ARC_EDGED:用直线将起始和结束点与中心点相连,和 IMG_ARC_NOFILL 一起使用是画饼状图轮廓的好方法。
<?php
    $img = imagecreate(300, 100);
    imagecolorallocate($img, 255, 255, 255);
    $blue = imagecolorallocate($img, 0, 0, 255);
    $red = imagecolorallocate($img, 255, 0, 0);
    imagearc($img, 50, 50, 50, 80, 0, 270, $blue);
    imagefilledarc($img, 125, 50, 60, 40, 90, 45, $red, IMG_ARC_PIE);
    imagefilledarc($img, 128, 55, 60, 40, 90, 45, $blue, IMG_ARC_CHORD);
    imagefilledarc($img, 200, 55, 80, 70, 180, 100, $blue, IMG_ARC_EDGED|IMG_ARC_NOFILL);
    header('Content-type:image/jpeg');
    imagejpeg($img);
    imagedestroy($img);
?>
⑦ 绘制文字
函数名 描述
imagestring() 水平绘制一行字符串
imagestringup() 垂直绘制一行字符串
imagechar() 水平绘制一个字符
imagecharup() 垂直绘制一个字符
imagettftext() 用 TrueType 字体向图像中写入文本

语法格式如下:
imagestring(resource $image, int $font, int $x, int $y, string $s, int $color)
imagestringup(resource $image, int $font, int $x, int $y, string $s, int $col)
imagechar(resource $image, int $font, int $x, int $y, string $c, int $color)
imagecharup(resource $image, int $font, int $x, int $y, string $c, int $color)
使用这些函数可以在画布 $image 上,坐标为($x,$y)的位置,绘制字符串(或字符) $s,字符串的颜色为 $color,字体为 $font。如果 $font 是 1,2,3,4 或 5,则使用内置字体。

<?php
    $str = 'https://xiyoudaodao.gitee.io';
    $img = imagecreate(300, 200);
    imagecolorallocate($img, 255, 255, 255);
    $red = imagecolorallocate($img, 255, 0, 0);
    imagestring($img, 5, 0, 0, $str, $red);
    imagestringup($img, 2, 150, 180, $str, $red);
    imagechar($img, 3, 50, 50, $str, $red);
    imagecharup($img, 4, 50, 100, $str, $red);
    header('Content-type:image/jpeg');
    imagejpeg($img);
    imagedestroy($img);
?>

绘制文本文字

  • imagettftext(resource $image, float $size, float $angle, int $x, int $y, int $color, string $fontfile, string $text)
    • $image:由图象创建函数(例如 imagecreatetruecolor())返回的图象资源;
    • $size:字体的尺寸;
    • $angle:角度制表示的角度,0 度为从左向右读的文本,数值越高则表示将文本进行逆时针旋转。例如 90 度表示从下向上读的文本;
    • $x、$y:表示文本中第一个字符的坐标点(大概是字符左下角的位置);
    • $color:用来设置文本的颜色;
    • $fontfile:是要使用的 TrueType 字体文件的路径;
    • $text:UTF-8 编码的文本字符串。
<?php
    $str1 = 'https://xiyoudaodao.gitee.io';
    $str2 = '西柚叨叨的博客';
    $font = 'C:\Windows\Fonts\STCAIYUN.TTF';
    $img = imagecreate(300, 300);
    imagecolorallocate($img, 255, 255, 255);
    $black = imagecolorallocate($img, 0, 0, 0);
    imagettftext($img, 16, 0, 80, 150, $black, $font, $str2);
    imagettftext($img, 16, 90, 150, 295, $black, $font, $str1);
    imagettftext($img, 16, 135, 260, 250, $black, $font, $str1);
    imagettftext($img, 16, 45, 40, 250, $black, $font, $str1);
    header('Content-type:image/jpeg');
    imagejpeg($img);
    imagedestroy($img);
?>
⑧ 获取图片信息

getimagesize(string $filename, array &$imageinfo = ?): array
可以获取指定图形的尺寸、宽度、高度和类型等信息

<?php
    print_r(getimagesize("https://xiyoudaodao.gitee.io/css/images/logo.png"));
?>
⑨ 复制图像

复制图像

  • imagecopy(resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $src_w, int $src_h) 将 $src_im 图像中坐标($src_x,$src_y)的位置,拷贝一份宽度为 $src_w,高度为 $src_h 的矩形区域到 $dst_im 图像中坐标为 ($dst_x,$dst_y) 的位置上。
<?php
    header("Content-type: image/jpeg");
    $image1 = imagecreate(300, 300);
    imagecolorallocate($image1, 255, 255, 255);
    $image2=imagecreatefrompng("https://xiyoudaodao.gitee.io/css/images/logo.png");
    imagecopy($image1,$image2,50,0,25,0,120,120);	//复制图片的一部分
    imagepng($image1);					//输出图形$image1
    imagedestroy($image1);
    imagedestroy($image2);
?>

复制图像并调整大小
  当我们将图片上传到服务器时,为了节省存储空间往往需要将图片进行压缩,同时也可以提高网页加载的速度。压缩通常是指将图片按比例进行缩放,以此来减少图片的体积。
  PHP中压缩图片可以使用 imagecopyresized() 或者 imagecopyresampled() 函数,而使用 imagecopyresampled() 函数处理后图片的质量会好一些,所以在进行图片压缩时可以优先使用 imagecopyresampled() 函数。

  • imagecopyresized(resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h)
  • imagecopyresampled(resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h)
    • $dst_image:目标图象连接资源。
    • $src_image:源图象连接资源。
    • $dst_x:目标 X 坐标点。
    • $dst_y:目标 Y 坐标点。
    • $src_x:源的 X 坐标点。
    • $src_y:源的 Y 坐标点。
    • $dst_w:目标宽度。
    • $dst_h:目标高度。
    • $src_w:源图象的宽度。
    • $src_h:源图象的高度。 这两个函数都可以将一幅图像中的一块矩形区域拷贝到另一个图像中,而 imagecopyresampled() 函数更是可以平滑地插入像素值,因此,在减小了图像的大小的同时仍然保持极大的清晰度。
<?php
    /**
     * @param  $file  要缩放的图片路径
     * @param  $width 缩放后的宽度
     * @param  $height缩放后的高度
     * @param  $eq    是否等比缩放
     * @return [type]
     */
    function compress($file,$width,$height='',$eq=true){
        $image = imagecreatefrompng($file);
        $img_info = getimagesize($file);
        if($eq) $height = $img_info[1]*($width/$img_info[0]);
        $com_image = imagecreatetruecolor($width, $height);
        imagecopyresampled($com_image, $image, 0, 0, 0, 0, $width, $height, $img_info[0], $img_info[1]);
        header('Content-type:image/png');
        imagepng($com_image);
        imagedestroy($com_image);
    }
    $file = 'https://xiyoudaodao.gitee.io/css/images/logo.png';
    compress($file, 200);


    /**
     * @param  $file    需要裁剪的原图
     * @param  $x       裁剪的起始位置的X坐标
     * @param  $y       裁剪的起始位置的Y坐标
     * @param  $width   裁剪的区域的宽度
     * @param  $height  裁剪的区域的高度
     * @return [type]
     */
    function compress($file,$x,$y,$width,$height){
        $image = imagecreatefrompng($file);
        $com_image = imagecreatetruecolor($width, $height);
        imagecopyresampled($com_image, $image, 0, 0, $x, $y, $width, $height, $width, $height);
        header('Content-type:image/jpeg');
        imagejpeg($com_image);
        imagedestroy($com_image);
    }
    $file = 'https://xiyoudaodao.gitee.io/css/images/logo.png';
    compress($file,0,0,20,60);
?>

三、综合案例

1、生成验证码

  • 具体的实现步骤如下所示:
    • 创建画布;
    • 随机绘制字符;
    • 绘制干扰元素;
    • 输出图像到浏览器;
    • 释放资源。
<?php
    function rand_str($length) {
        // 验证码中所需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for($i = 0; $i < $length; $i++)
        {
            // 随机截取 $chars 中的任意一位字符;
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    function rand_color($image){
        // 生成随机颜色
        return imagecolorallocate($image, rand(127, 255), rand(127, 255), rand(127, 255));
    }
    $image = imagecreate(200, 100);
    imagecolorallocate($image, 0, 0, 0);
    for ($i=0; $i <= 9; $i++) {
        // 绘制随机的干扰线条
        imageline($image, rand(0, 200), rand(0, 100), rand(0, 200), rand(0, 100), rand_color($image));
    }
    for ($i=0; $i <= 100; $i++) {
        // 绘制随机的干扰点
        imagesetpixel($image, rand(0, 200), rand(0, 100), rand_color($image));
    }
    $length = 4;//验证码长度
    $str = rand_str($length);//获取验证码
    $font = 'C:\Windows\Fonts\simhei.ttf';
    for ($i=0; $i < $length; $i++) {
        // 逐个绘制验证码中的字符
        imagettftext($image, rand(20, 38), rand(0, 60), $i*50+25, rand(30,70), rand_color($image), $font, $str[$i]);
    }
    header('Content-type:image/jpeg');
    imagejpeg($image);
    imagedestroy($image);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <img src="index.php" id="refresh" onclick="this.src='index.php?'+Math.random()">
    <a href="javacript:;" onclick="document.getElementById('refresh').src='index.php?'+Math.random();">看不清,换一张</a>
</body>
</html>

2、为图片添加水印

<?php
    /**
     * [watermark description]
     * @param  string  $img              [待加水印的图片地址]
     * @param  string  $watermark        [水印图片地址]
     * @param  integer $district         [水印的位置]
     * @param  integer $watermarkquality [图片水印的质量]
     * @return                           [添加水印的图片]
     */
    function watermark($img, $watermark, $district = 0,$watermarkquality = 95){
        $imginfo = @getimagesize($img);
        $watermarkinfo = @getimagesize($watermark);
        $img_w = $imginfo[0];
        $img_h = $imginfo[1];
        $watermark_w = $watermarkinfo[0];
        $watermark_h = $watermarkinfo[1];
        if($district == 0) $district = rand(1,9);
        if(!is_int($district) OR 1 > $district OR $district > 9) $district = 9;
        switch($district){
            case 1:
                $x = +5;
                $y = +5;
                break;
            case 2:
                $x = ($img_w - $watermark_w) / 2;
                $y = +5;
                break;
            case 3:
                $x = $img_w - $watermark_w - 5;
                $y = +5;
                break;
            case 4:
                $x = +5;
                $y = ($img_h - $watermark_h) / 2;
                break;
            case 5:
                $x = ($img_w - $watermark_w) / 2;
                $y = ($img_h - $watermark_h) / 2;
                break;
            case 6:
                $x = $img_w - $watermark_w;
                $y = ($img_h - $watermark_h) / 2;
                break;
            case 7:
                $x = +5;
                $y = $img_h - $watermark_h - 5;
                break;
            case 8:
                $x = ($img_w - $watermark_w) / 2;
                $y = $img_h - $watermark_h - 5;
                break;
            case 9:
                $x = $img_w - $watermark_w - 5;
                $y = $img_h - $watermark_h - 5;
                break;
        }
        switch ($imginfo[2]) {
            case 1:
                $im = @imagecreatefromgif($img);
                break;
            case 2:
                $im = @imagecreatefromjpeg($img);
                break;
            case 3:
                $im = @imagecreatefrompng($img);
                break;
        }
        switch ($watermarkinfo[2]) {
            case 1:
                $watermark_logo = @imagecreatefromgif($watermark);
                break;
            case 2:
                $watermark_logo = @imagecreatefromjpeg($watermark);
                break;
            case 3:
                $watermark_logo = @imagecreatefrompng($watermark);
                break;
        }
        if(!$im or !$watermark_logo) return false;
        $dim = @imagecreatetruecolor($img_w, $img_h);
        if(@imagecopy($dim, $im, 0, 0, 0, 0,$img_w,$img_h )){
            imagecopy($dim, $watermark_logo, $x, $y, 0, 0, $watermark_w, $watermark_h);
        }
        $file = dirname($img) . '/w' . basename($img);
        $result = imagejpeg ($dim,$file,$watermarkquality);
        imagedestroy($watermark_logo);
        imagedestroy($dim);
        imagedestroy($im);
        if($result){
            echo $img.' 水印添加成功';
            return;
        }
        else {
            return false;
        }
    }
    $file = './back.gif';   //待加水印的图片地址
    $water = 'https://xiyoudaodao.gitee.io/css/images/logo.png';  //水印图片的地址
    watermark($file, $water);
?>

关注微信公众号,与我交流吧~

分享