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);
?>
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。