【发布时间】:2010-10-01 18:44:44
【问题描述】:
我有一个占位符图片,上面写着:
Your rating is:
[rating here]
我的 PHP 代码应该在占位符图像上的空白处动态插入评级数字。我该怎么做?
【问题讨论】:
标签: php image image-processing image-manipulation gd
我有一个占位符图片,上面写着:
Your rating is:
[rating here]
我的 PHP 代码应该在占位符图像上的空白处动态插入评级数字。我该怎么做?
【问题讨论】:
标签: php image image-processing image-manipulation gd
这里有一个例子,你可以如何做到这一点 - 使用gd function 调用来制作你的图像,但播放得很好并缓存图像。此示例通过确保如果浏览器已经拥有所需的图像,它会返回一个 304...
,从而播放更好#here's where we'll store the cached images
$cachedir=$_SERVER['DOCUMENT_ROOT'].'/imgcache/'
#get the score and sanitize it
$score=$_GET['score'];
if (preg_match('/^[0-9]\.[0-9]{1,2}$/', $score)
{
#figure out filename of cached file
$file=$cachedir.'score'.$score.'gif';
#regenerate cached image
if (!file_exists($file))
{
#generate image - this is lifted straight from the php
#manual, you'll need to work out how to make your
#image, but this will get you started
#load a background image
$im = imagecreatefrompng("images/button1.png");
#allocate color for the text
$orange = imagecolorallocate($im, 220, 210, 60);
#attempt to centralise the text
$px = (imagesx($im) - 7.5 * strlen($score)) / 2;
imagestring($im, 3, $px, 9, $score, $orange);
#save to cache
imagegif($im, $file);
imagedestroy($im);
}
#return image to browser, but return a 304 if they already have it
$mtime=filemtime($file);
$headers = apache_request_headers();
if (isset($headers['If-Modified-Since']) &&
(strtotime($headers['If-Modified-Since']) >= $mtime))
{
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT', true, 304);
exit;
}
header('Content-Type:image/gif');
header('Content-Length: '.filesize($file));
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT');
readfile($file);
}
else
{
header("HTTP/1.0 401 Invalid score requested");
}
如果你把它放在 image.php 中,你会在一个图像标签中使用如下
<img src="image.php?score=5.5" alt="5.5" />
【讨论】:
使用范围从 0 到 9 的静态图像,只需将它们组合在页面上即可构建大数字:
Your Rating: [image1.jpg][image2.jpg][image3.jpg]
【讨论】:
我知道问题是“如何动态创建带有指定数字的图像?”但我将解决根本问题。动态图像处理对 CPU 的负担很重。只是不要这样做。当然不要在网络请求的上下文中这样做。考虑使用静态图像,然后根据评分显示正确的图像。即使您的评分系统一直达到 100,拥有 100 张静态图像也比一遍又一遍地重绘同一张图像要好。
【讨论】:
另见 alpha 混合示例 http://ca3.php.net/manual/en/function.imagecopymerge.php#73477
而不是使用 imagestring() 来编写内置或 TTF 字体, 您可以创建自己的 0-9 个字符作为 24 位 PNG 图像 alpha 混合,然后使用 imagecopymerge() 将它们合成。这需要更多的工作,但会给你更多的控制权 字符集的外观。
【讨论】:
为什么不将数字设置为 div 中的文本,然后使用字体和背景选择设置样式?
【讨论】: