代码之家  ›  专栏  ›  技术社区  ›  Ali

如何动态创建带有指定数字的图像?

  •  4
  • Ali  · 技术社区  · 16 年前

    我有一张持仓者的照片,上面写着:

    Your rating is:
       [rating here]
    

    我的PHP代码应该动态地插入评级编号,在占位符图像上为其留出空白。我该怎么做?

    5 回复  |  直到 16 年前
        1
  •  8
  •   Paul Dixon    16 年前

    下面是一个例子,你如何做到这一点-使用 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中,您将在image标记中使用如下内容

    <img src="image.php?score=5.5" alt="5.5" />
    
        2
  •  2
  •   Gerhard    16 年前

    使用从0到9的静态图像,只需在页面上组合它们即可生成大量图像:

    Your Rating: [image1.jpg][image2.jpg][image3.jpg]

        3
  •  1
  •   Al W    16 年前

    我知道问题是“如何动态地创建具有指定数字的图像?”但我会解决潜在的问题。动态图像处理对CPU来说很重。别这么做。当然,不要在Web请求的上下文中这样做。考虑使用静态图像,然后根据评级显示正确的图像。即使您的分级系统一直到100,拥有100个静态图像也比一遍又一遍地重新绘制相同的图像要好。

        4
  •  0
  •   Hugh Bothwell    16 年前

    另请参见alpha混合示例 http://ca3.php.net/manual/en/function.imagecopymerge.php#73477

    而不是使用imageString()使用内置字体或ttf字体进行写入, 您可以创建自己的0-9字符作为24位PNG图像, alpha混合,然后将它们与imagecopymerge()组合在一起。这是一个更多的工作,但会给你更多的控制权 字符集的外观。

        5
  •  0
  •   John Dunagan    16 年前

    为什么不将数字设置为DIV中的文本,然后用字体和背景选项设置它的样式?