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

应用PHP GD库制作占位图片服务

2013-12-20 10:41 218 查看

1.缘由

作为一个完美主义者,我们在重构结束后,会给页面内的图片增加尺寸示意图,清晰直观的给后续的编辑工作提供指引。所以我们就需要制作一张长成这样的占位图片,当页面内尺寸较多的时候,光是做这个图片的过程都足以让人心烦。

  如



2.偷懒

  我们都喜欢将一些重复性的工作用程序来“偷懒”,比如Zen Coding,Sass。既然上面这个图片很简单,只需要一个数字表示当前大小,我们是不是可以“偷一下懒”呢。

  说到图片生成,别的不会,只好想到我们的PHP GD库了~

  1.首先是传参,我们需要确定的是图片尺寸(必须),图片颜色(可选),图片文本(可选),文本颜色(可选),图片类型)(可选)。

  

http://site.com/img.php?x=长x宽.类型/图片颜色/文本颜色&text=图片文本


当然,这样的路径还是太复杂了些,所以我们为了尽量减少路径的复杂度,使用了.htaccess来定义我们的rewrite(尽管只是少输入了 'img.php?x=',也是少了,不是吗^_^)

RewriteEngine On
RewriteRule ^([\d].*) img.php?x=$1


这样,我们就可以使用如下的url来生成图片了

http://site.com/长x宽.类型/图片颜色/文本颜色&text=图片文本


当然,我们可以自定义一些常用的尺寸,

#Square Pop Up 250x250
RewriteRule ^(s\w+pop)(.*) img.php?x=250x250$2


  2.处理参数

$x = strtolower($_GET["x"]); //GET the query string from the URL.
$x_pieces = explode('/',$x);//GET the arguments.


除了尺寸,其他的参数我们都给一个默认值,特别的,我们对尺寸方面我们的处理比较细致,

$dimensions = explode('x',$x_pieces[0]); //dimensions are always the first paramter in the URL.

$width = preg_replace('/[^\d:\.]/i', '',$dimensions[0]); //Filters out any characters that are not numbers, colons or decimal points.
$height = $width;
if ($dimensions[1]) {
$height = preg_replace('/[^\d:\.]/i', '',$dimensions[1]); //Filters out any characters that are not numbers, colons or decimal points.
}

if( $width < 1 || $height < 1 ) {
die("Too small of an image!"); //If it is too small we kill the script.
}

//If one of the dimensions has a colon in it, we can calculate the aspect ratio. Chances are the height will contain a ratio, so we'll check that first.
if( preg_match ( '/:/' , $height) ) {
$ratio = explode(':', $height);
//If we only have one ratio value, set the other value to the same value of the first making it a ratio of 1.
if ( !$ratio[1] ) {
$ratio[1] = $ratio[0];
}
if ( !$ratio[0] ) {
$ratio[0] = $ratio[1];
}
$height = ( $width * $ratio[1]) / $ratio[0];

} else if( preg_match ( '/:/' , $width) ) {
$ratio = explode(':', $width);
//If we only have one ratio value, set the other value to the same value of the first making it a ratio of 1.
if ( !$ratio[1] ) {
$ratio[1] = $ratio[0];
}
if ( !$ratio[0] ) {
$ratio[0] = $ratio[1];
}
$width = ($height * $ratio[0]) / $ratio[1];
}

$area = $width * $height;
if ($area >= 16000000 || $width > 9999 || $height > 9999) { //Limit the size of the image to no more than an area of 16,000,000.
die("Too big of an image!"); //If it is too big we kill the script.
}


3.生成图片

接下来就没什么好说了,使用GD库生成图片,如果有文本,给文本定大小,定位,然后生成文本,给个图片头,哦了

PS:在这个过程中,遇到一个问题,图片的尺寸我是希望可以用比例来表示的,如600x3:2, 也就是等于600x400,

但在win下的apache的RewriteRule中,Apache 2之后的版本对于URL目录中有冒号(:, colon)的会做特殊处理,因为冒号在Windows下被用于盘符标识的一部分,在碰到这样包含冒号的路径时,Apache会以权限的名义直接禁止访问。放狗搜了下也没找到什么解决办法,希望有知道的朋友告知一下,感激不尽。

附:http://cued.html-5.me/ 这个图片占位服务暂时放在这个免费空间下(byethost这个国外的免费空间还是挺不错的)。如有改动我会通知在这里,谢谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: