php实现图片占位符

1、首先导入字体文件

2、新建文件添加信息

<?php
error_reporting(E_ALL);
/**
 * 完整的url 模式
 * http://oauth.xxxxx.com/img.php/w/380/h/289/bg/123456/tc/cccccc/t/hello
 * */
$width = 380;
$height = 285;
$bgColor = 'c7c7c7';
$textColor = '000000';
$text = "";
if (isset($_SERVER['DOCUMENT_URI'])) {
    $url = $_SERVER['DOCUMENT_URI'];
    $arr = explode("/", $url);
    $count = count($arr);//查看参数数量
    if ($count > 3) {
        for ($i=2; $i <= $count; $i=$i+2) { 
            if (isset($arr[$i]) && isset($arr[$i+1])) {
                if ($arr[$i] === 'w') {
                    $width = intval($arr[$i+1]);//图片宽度
                }
                if ($arr[$i] === 'h') {
                    $height = intval($arr[$i+1]);//图片高度
                }
                if ($arr[$i] === 'bg') {
                    $bgColor = $arr[$i+1];//背景
                }
                if ($arr[$i] === 'tc') {
                    $textColor = $arr[$i+1];//字体颜色
                }
                if ($arr[$i] === 't') {
                    $text = $arr[$i+1];//字体信息
                }
            }
        }
    }
}
if (empty($text)) {
    $text = $width.'x'.$height;
}
// 接收请求参数,设置默认值
/*$width = isset($_GET['width'])? intval($_GET['width']) : 380;
$height = isset($_GET['height'])? intval($_GET['height']) : 285;
$bgColor = isset($_GET['bg'])? $_GET['bg'] : 'c7c7c7';
$textColor = isset($_GET['text_color'])? $_GET['text_color'] : '000000';
$text = isset($_GET['text'])? $_GET['text'] : $width.'x'.$height;*/

// 创建一个空白图像
$image = imagecreatetruecolor($width, $height);

//将16进制转成rgb
function hex2rgb($hexColor) {
    // 去除十六进制颜色代码中的#符号
    $hexColor = ltrim($hexColor, '#');
    // 使用sscanf解析颜色代码的两个字符为一组,生成RGB值
    if (strlen($hexColor) == 3) {
        // 如果是简短的十六进制颜色代码,重复每个字符
        $hexColor = $hexColor[0] . $hexColor[0] . $hexColor[1] . $hexColor[1] . $hexColor[2] . $hexColor[2];
    }
    // 使用sscanf解析颜色代码
    return array_map('hexdec', str_split($hexColor, 2));
}

// 背景颜色
$bgRGB = hex2rgb($bgColor);
$bg = imagecolorallocate($image, $bgRGB[0], $bgRGB[1], $bgRGB[2]);

// 文本颜色
$textRGB = hex2rgb($textColor);
$textColor = imagecolorallocate($image, $textRGB[0], $textRGB[1], $textRGB[2]);

// 填充背景
imagefill($image, 0, 0, $bg);

// 添加文本(可选)
$fontSize = $width/(strlen($text)+5); // 字体大小
$font = realpath("./simhei.ttf");//字体需要绝对路径
$textBox = imagettfbbox($fontSize, 0, $font, $text);
$textWidth = $textBox[2] - $textBox[0];
$textHeight = $textBox[7] - $textBox[1];
$x = ($width - $textWidth) / 2;
$y = ($height - $textHeight) / 2;
imagettftext($image, $fontSize, 0, $x, $y, $textColor, $font, $text);

// 输出图像
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
?>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容