PHP图像处理函数实战:像素级文字着色示例
在学习过程中,保持“玩”的心态至关重要。制造成就感能显著提升学习效果与热情,
从而让人更喜爱自己钻研的内容!
以下举例说明:
今日学习PHP图像函数模块,涉及几个关键函数:
getimagesize()
array getimagesize ( string $filename [, array &$imageinfo ] )
getimagesize() 函数可测定GIF、JPG、PNG、SWF、SWC、PSD、TIFF、BMP、IFF、JP2、JPX、JB2、JPC、XBM或WBMP等图像文件的大小,并返回图像尺寸、文件类型及可用于HTML IMG标签的height/width文本字符串。
imagecreatefromgif()
resource imagecreatefromgif ( string $filename )
imagecreatefromgif() 返回一个图像标识符,代表从指定文件名取得的图像。
这意味着为了后续方便使用该图片资源,此函数返回一个操作句柄。
类似函数还有imagecreatefromjpeg()、imagecreatefrompng()等,更多细节可查阅官方在线手册。
imagecolorat()
int imagecolorat ( resource $image , int $x , int $y )
返回指定图像中特定位置像素的颜色索引值。
imagecolorsforindex()
array imagecolorsforindex ( resource $image , int $index )
本函数返回一个包含red、green、blue和alpha键名的关联数组,提供指定颜色索引对应的具体数值。
阅读上述生硬的介绍可能令人困倦,但请坚持一下!
掌握这些函数后,如何进行练习呢?
学到此处,我立刻想到一个有趣的实践项目!
是什么呢?猜猜看~!!!!
请看代码:
<?php
$url = "logo-yy.gif";
$size = getimagesize($url);
$width = $size[0];
$height = $size[1];
$im = imagecreatefromgif($url);
for($y=1;$y<$height;$y++){
for($x=1;$x<$width;$x++){
$color_index = imagecolorat($im, $x, $y);
$color_tran = imagecolorsforindex($im, $color_index);
echo("
<span class='\"c\"' style="\"color:RGB(".$color_tran['red'].",".$color_tran['green'].",".$color_tran['blue'].");\"">");
echo("爱");
echo("</span>");
}
echo("
");
}
?> 需注意,程序中使用的函数是imagecreatefromgif(),
因此变量$url指向的文件应为GIF格式;若指向JPG格式文件,则需使用imagecreatefromjpeg()。
当然,我们可以整合逻辑,因为第一个函数即可判断图片格式,此处暂不展开!哈哈
好了,拥有PHP环境的读者赶紧试试效果吧!呵呵
不建议使用过大的图片!小Logo即可!
否则,别怪我没提前告知啊!
此例虽无实际用途,但能激发大家学习的乐趣!!
献给正在学习PHP的人!