php 画图片2

<?php
    
    // 使用php操作gd库做图
    // 1. 创建一个画布资源
    $im = imagecreatetruecolor(200, 50);

    // 2. 创建背景色
    // 2.1 得到背景颜色
    $bg_color = imagecolorallocate($im, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
    // 2.2 填充画布
    imagefill($im, 0, 0, $bg_color);

    // 3. 获取验证码数据
    $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789';
    
    $captcha = '';
    for( $i = 0; $i < 5; $i++ ){
        //随机从字符串中取一个, 加入到captcha;
        $captcha .= $str[mt_rand(0, strlen($str) - 1)] . ' ';
    }

    // 增加干扰线
    for( $i = 0; $i < 10; $i++ ){
        // 1.得到干扰线颜色
        $line_color = imagecolorallocate($im, mt_rand(100, 200), mt_rand(100, 200), mt_rand(100, 200));

        // 2.画线
        imageline($im, mt_rand(0, 200), mt_rand(0, 50), mt_rand(0, 200), mt_rand(0, 50), $line_color);
    }

      // 增加干扰点
    for( $i = 0; $i < 200; $i++ ){
        // 给点分配颜色
        $pixel_color = imagecolorallocate($im, mt_rand(100, 200), mt_rand(100, 200), mt_rand(100, 200));
        // 画点
        imagesetpixel($im, mt_rand(0, 200), mt_rand(0, 50), $pixel_color);

    }

    // 4.将验证码写入图片
    // 4.1得到文字的颜色
    $str_color = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 200), mt_rand(0, 200));

    // 4.2 将字符串写入图片
    imagestring($im, 5, 60, 20, $captcha, $str_color); 

    // 5. 指定类型
    header('Content-type:image/png');

    // 6. 查看图片
    // imagepng($im); 
    imagepng($im, 'test2.png');

    // 7. 释放资源
    imagedestroy($im);
原文地址:https://www.cnblogs.com/zsongs/p/6099699.html