场景:网站统计代码,在用户网站是,根据一个字段值,显示图片或文字水印图片icon
public function createIcon($icon)
{
//图标类型 0:不显示 1:默认 2:默认(篮色) 3:默认(绿) 4:默认(紫) 10:文字显示
$config = config('img');
$width = $config['width'];
$widthTxt = $config['width_txt'];
$height = $config['height'];
$bgRed = $config['bg_red'];
$bgGreen = $config['bg_green'];
$bgBlue = $config['bg_blue'];
$textRed = $config['text_red'];
$textGreen = $config['text_green'];
$textBlue = $config['text_blue'];
$ds = DIRECTORY_SEPARATOR;
$rootDir = $_SERVER['DOCUMENT_ROOT'];
//图片或文字时,显示的宽度不一样
$hbWidth = $icon == 10 ? $widthTxt : $width;
//画布
if (function_exists('imagecreatetruecolor')) {
$hb = imagecreatetruecolor($hbWidth, $height);
} else {
$hb = imagecreate($hbWidth, $height);
}
if ($icon > 0 && $icon <= 4) {
//显示icon图片
$img = $rootDir . $ds . 'source' . $ds . 'img' . $ds . $this->img[$icon];
$source = imagecreatefrompng($img);
imagecopyresampled($hb, $source, 0, 0, 0, 0, $width, $height, $width, $height);
imagepng($hb);
imagedestroy($source);
} else if ($icon == 10) {
//显示文字icon
//图片背景
$background = imagecolorallocate($hb, $bgRed, $bgGreen, $bgBlue);
//填充背景
imagefill($hb, 0, 0, $background);
//字体颜色
$black = imagecolorallocate($hb, $textRed, $textGreen, $textBlue);
//字体文件
$font = $rootDir . $ds . 'source' . $ds . 'font' . $ds . 'simsun.ttc';
//显示的文字
$defaultTxt = $config['default_txt'];
//将文本写入图像:4个数字依次为:字号,旋转角度,padding-left,padding-top
imagefttext($hb, 10, 0, 0, 16, $black, $font, $defaultTxt);
imagepng($hb);
}
imagedestroy($hb);
}