如何动态地创建上有一个指定数量的图像?
-
19-08-2019 - |
题
我有一个位置保持图像说是这样的:
Your rating is:
[rating here]
我的PHP代码应该动态插入等级数,其中有占位符图像上离开了它的空白区域。我该怎么办呢?
解决方案
下面是一个例子,你如何能做到这一点 - 使用 GD功能通话,让您的图像,但发挥好和高速缓存的图像。该样品戏剧甚至更好通过确保如果浏览器已经具有所需的图像,则返回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图片 α混合,然后复合它们与imagecopymerge()。这是一个有点更多的工作,但将让您欣赏到更多的控制 看的字符集的。
为什么不设置一个div作为文本的数字,然后用字体和背景样式选择它?
不隶属于 StackOverflow