常用 GD 辅助代码片

生成海报+二维码

/**
 * 生成二维码海报 (执行后直接输出显示)
 *
 * @param string $bg_filename 背景图片文件名, 可以是网络图片
 * @param string $qrcode_filename 二维码图片文件名, 可以是网络图片
 * @param integer $qrcode_width 二维码定义宽度
 * @param integer $qrcode_height 二维码定义高度
 * @param integer $x 二维码距左边
 * @param integer $y 二维码距顶边
 * @return void
 */
function out_poster(string $bg_filename, string $qrcode_filename, int $qrcode_width, int $qrcode_height, int $x, int $y)
{
    // 背景图
    $bg_im = imagecreatefromstring(file_get_contents($bg_filename));

    // 二维码
    $qrcode_blob = file_get_contents($qrcode_filename);
    $qrcode_im = imagecreatefromstring($qrcode_blob);
    list($width_orig, $height_orig) = getimagesizefromstring($qrcode_blob);

    // 缩放二维码
    $new_qrcode = imagecreatetruecolor($qrcode_width, $qrcode_height);
    imagecopyresampled($new_qrcode, $qrcode_im, 0, 0, 0, 0, $qrcode_width, $qrcode_height, $width_orig, $height_orig);
    imagedestroy($qrcode_im);


    // 透明度
    $alpha = 100;

    // 合并图片
    imagecopymerge($bg_im, $new_qrcode, $x, $y, 0, 0, $qrcode_width, $qrcode_height, $alpha);

    // 合并输出格式
    header('Content-type: image/jpeg');

    imagejpeg($bg_im);
    // 释放资源
    imagedestroy($bg_im);
    imagedestroy($new_qrcode);
    exit;
}


// 使用示例:
out_poster('./bg.png', 'https://ncstatic.clewm.net/feres/a44fa42f_4030f330_1651056214.png', 760, 760, 650, 5630);

压缩图片

/**
 * 压缩图片 (支持: png/jpg/jpeg/gif/bmp)
 *
 * @param string $filename 源文件
 * @param string $out_filename 输出文件
 * @param integer $quality 压缩率, 默认 70
 * @return bool
 */
function image_zlib(string $filename, string $out_filename, int $quality = 70):bool
{
    $ext = substr(strrchr($filename, '.'), 1);
    if ($ext == 'png' || $ext == 'jpg' || $ext == 'jpeg' || $ext == 'bmp' || $ext == 'gif') {
        ini_set("memory_limit", "256M"); //修改php分配的内存
        $percent = 1;
        // 内容类型
        header('Content-Type: image/jpeg');
        // 获取新的尺寸
        list($width, $height) = getimagesize($filename);
        $new_width = $width; //* $percent;
        $new_height = $height; //* $percent;
        // 重新取样
        $image_p = imagecreatetruecolor($new_width, $new_height);
        $image = imagecreatefromstring(file_get_contents($filename));
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        // 输出
        imagejpeg($image_p, $out_filename, $quality);
        return true;
    } 
    return false;
}

// 使用示例:
image_zlib('./bg.png', './woc.jpg', 50);

图片写字

header('Content-type: image/jpeg');

$dst = "static/image/auth.jpg";
$source = imagecreatefromjpeg($dst);   //设定背景图片
$white = imagecolorallocate($source, 0, 0, 0);  //设定字体颜色
imagettftext($source, 80, 0, 825, 2500, $white, 'static/font/yahei.ttf', 'by 剑齿虎');
imagettftext($source, 80, 0, 825, 2673, $white, 'static/font/yahei.ttf', date('Y年m月d日'));

imagejpeg($source);
imagedestroy($source);
exit;
Last Updated:
Contributors: 余小波