Php 如何动态创建带有指定编号的图像?
我有一张占位符图片,上面写着:Php 如何动态创建带有指定编号的图像?,php,image,image-processing,image-manipulation,gd,Php,Image,Image Processing,Image Manipulation,Gd,我有一张占位符图片,上面写着: Your rating is: [rating here] 我的PHP代码应该在占位符图像上的空白处动态插入评级编号。我怎样才能做到这一点?我知道问题是“如何动态创建一个带有指定数字的图像?”但我将解决根本问题。动态图像处理对CPU来说是一项繁重的任务。不要这样做。当然,不要在web请求的上下文中这样做。考虑静态图像,然后根据评级显示正确的图像。即使你的评级系统一直到100,拥有100张静态图像也比一遍又一遍地重画同一张图像要好。这里有一个例子,你可以这样
Your rating is:
[rating here]
我的PHP代码应该在占位符图像上的空白处动态插入评级编号。我怎样才能做到这一点?我知道问题是“如何动态创建一个带有指定数字的图像?”但我将解决根本问题。动态图像处理对CPU来说是一项繁重的任务。不要这样做。当然,不要在web请求的上下文中这样做。考虑静态图像,然后根据评级显示正确的图像。即使你的评级系统一直到100,拥有100张静态图像也比一遍又一遍地重画同一张图像要好。这里有一个例子,你可以这样做-使用调用来制作图像,但要播放好并缓存图像。此示例通过确保如果浏览器已经具有所需的图像,则返回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的静态图像,只需在页面上组合它们即可生成大量图像:
您的评级:[image1.jpg][image2.jpg][image3.jpg]
另请参见
而不是使用imagestring()使用内置字体或TTF字体进行写入,
您可以使用创建自己的0-9个字符作为24位PNG图像
alpha混合,然后使用imagecopymerge()将其合成。这是一个多一点的工作,但会给你更多的控制权
字符集的外观。为什么不将数字设置为div中的文本,然后使用字体和背景选项设置其样式?事实上,它可以是0.1到9.99之间的任意值,因此我不想手动执行此操作。同一图像不应生成两次-如果请求相同的图像,应在以后存储和检索它们。