php - 如何动态创建带有指定编号的图像?

标签 php image image-processing image-manipulation gd

我有一个占位符图像,内容如下:

Your rating is:
   [rating here]

我的 PHP 代码应该在占位符图像上留有空白的地方动态插入评分数字。我该怎么做?

最佳答案

这是一个如何做到这一点的例子 - 使用 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" />

关于php - 如何动态创建带有指定编号的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/449858/

相关文章:

c# - 动态文本转化为图像

c++ - 相同的功能但不同的结果

opencv - 使用 Tensorflow Api 和 Opencv 在视频上裁剪检测到的对象

PHP MySQL 获取结果并显示

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

php - Laravel:PHPUnit 导致 404 的一切

node.js - 在 React 中使用 index.js 导入多个图片资源

php - 如何在 codeigniter 中对列中的数据进行切片并根据它进行排序?

c++ - 从 2D 点阵列创建图像

python - 从 4 个角颜色插值的二维颜色渐变(256x256 矩阵)