您的位置:首页 > 编程语言 > PHP开发

对PHP中GD库的一些画图函数、及函数参数的学习总结(一)

2014-03-28 20:36 627 查看
<?php
$img = imagecreatetruecolor(600, 600);  //创建一个600px * 600px 的真彩色图像
$cornflowerblue = imagecolorallocate($img, 100,149,237);
imagefill($img, 0, 0, $cornflowerblue);  //填充背景色
//imagefill($img, 30, 30, $cornflowerblue);    和上面一行代码的效果一样,中间的数字参数的改变对填充背景色没有影响
header('Content-Type:image/png');       //告诉浏览器以什么方式显示
imagepng($img);                    //PNG 格式将图像输出到浏览器或文件
imagedestroy($img);             //销毁图像资源
?>
<?php
$img = imagecreate(600, 600);
$cornflowerblue = imagecolorallocate($img, 100,149,237);   //第一个颜色就默认为图片的背景颜色
$magenta = imagecolorallocate($img, 255, 0, 255);
$springgreen = imagecolorallocate($img, 0, 255, 127);
header('Content-Type:image/png');
imagepng($img);
imagedestroy($img);
?>

通过上面两段代码,我想表达imagecreatetruecolor()和imagecreate()创建的图像,添加背景颜色的区别。

下面的代码是从(10, 10 )开始画一个100px * 100px 的正方形,正方形的100px*100px 包括边框的像素。而这个正方形的边框是1像素,空白像素加两个边框的2个像素就是100像素:

<?php
$img = imagecreatetruecolor(600, 600);
$cornflowerblue = imagecolorallocate($img, 100,149,237);;
$black = imagecolorallocate($img, 0, 0, 0);
imagefill($img, 0, 0, $cornflowerblue);  //填充背景色
imagerectangle($img, 10, 10, 109, 109, $black);
header('Content-Type:image/png');
imagepng($img);
imagedestroy($img);
?>
通过仔细地测量,正方形的边框是从(11, 11)、(110, 110)开始画的。由此,如果我们要为这个600px * 600px的图片加上边框就得:

<?php
……
imagerectangle($img, 0, 0, 600 - 1, 600 - 1, $black);    //图片的长和宽减1
……
?>


再看:

<?php
……
imagesetpixel($img, 200, 300, $black);
……
?>
画出的点的坐标其实是(201, 301)。

画圆时:

<?php……
imageellipse($img, 200, 200, 100, 100, $black);
……
?>
圆心是(200, 200), 加上圆边的2个像素,此圆的长就是101,宽也是101。椭圆类似。

再来看画线时GD函数的表现:

<?php
……
imageline($img, 300, 300, 400, 400, $black);
……
?>
这条线段第一个点的坐标其实是(301, 301), 线段末点的坐标是(401, 401)。朋友们是不是有些明白了,php中的GD函数在画图时第一个开始点总是会比你在函数中指定的参数坐标值大1个像素。

再来看imagefilledarc()函数:

<?php
……
imagefilledarc($img, 200, 300, 300, 200, 0, 120, $black, IMG_ARC_PIE);
//imagefilledarc($img, 200, 300, 300, 200, 0, 120, $black, IMG_ARC_CHORD);
//imagefilledarc($img, 200, 300, 300, 200, 0, 120, $black, IMG_ARC_NOFILL);
//imagefilledarc($img, 200, 300, 300, 200, 0, 120, $black, IMG_ARC_EDGED);
……
?>
效果如下图所示:



来看一个有误差的函数 imagechar():

<?php
……
imagechar($img, 5, 100, 200, 'Z', $black);
……
?>
对于x轴,是在101像素就开始画了,但在y轴却有几像素的误差。

imagefontheight(int $font) 返回指定字体一个字符高度的像素值 如:imagefontheight(15) 将返回15。

array imagettftext( resource
$image
,float
$size
,float
$angle

,int
$x
,int
$y
,int
$color

,string
$fontfile
,string
$text
),其中的 x, y 手册的解释是:

x:由
x
y
所表示的坐标定义了第一个字符的基本点(大概是字符的左下角)。这和imagestring不同,其 x,y 定义了第一个字符的左上角。例如 "top left" 为 0, 0。

y:Y 坐标。它设定了字体基线的位置,不是字符的最底端。

我一看到那基线就把我给弄蒙了,查了一下资料,请看下图:



实际显示时,像素还是有一些偏差。毕竟像素只是一个相对单位,它和显示器的分辨率有关,有时出现误差也是在所难免,但在标准的一像素的情况下,了解一下php GD库的这些函数的参数标准还是很有必要的。

当然GD中还有很多其它的函数,这里我也就不一一细说了,大家有什么好的想法,或我的行文有错误,希望大家不吝指出,我不胜感激。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: