略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: 使用 PHP 创建 PNG 图像

2024-11-12

使用 PHP 创建 PNG 图像

示例 #1 使用 PHP 创建 PNG 图像

<?php

header
("Content-type: image/png");
$string $_GET['text'];
$im     imagecreatefrompng("images/button1.png");
$orange imagecolorallocate($im22021060);
$px     = (imagesx($im) - 7.5 strlen($string)) / 2;
imagestring($im3$px9$string$orange);
imagepng($im);
imagedestroy($im);

?>
本例程需要从带有 <img src="button.php?text=text"> 标签的页面调用。 上述 button.php 脚本将 "text" 字符串绘制到一个图像上, 在本例中图像文件为 "images/button1.png", 然后输出绘制后的图像。 当你需要经常修改图像上的文字时, 动态生成图像就可以省去了每次都重新制作图像的麻烦。
add a noteadd a note

User Contributed Notes 1 note

up
3
viishalkumarsahu at gmail dot com
5 years ago
Function to create random png images when requested for example...
<img src="create_image.php?s=008080_F_1000_200&t=Sample%20Image%20Drawn%20By%20PHP" alt="GD Library Example Image" >

here is create_image.php
<?php
$setting
= isset($_GET['s']) ? $_GET['s'] : "FFF_111_100_100";
$setting = explode("_",$setting );
$img = array();

switch (
$n = count($setting)) {
    case
$n > 4 :
    case
3:
       
$setting[3] = $setting[2];
    case
4:
       
$img['width'] = (int) $setting[2];
       
$img['height'] = (int) $setting[3];
    case
2:
       
$img['color'] = $setting[1];
       
$img['background'] = $setting[0];
        break;
    default:
        list(
$img['background'],$img['color'],$img['width'],$img['height']) = array('F','0',100,100);
        break;
}

$background = explode(",",hex2rgb($img['background']));
$color = explode(",",hex2rgb($img['color']));
$width = empty($img['width']) ? 100 : $img['width'];
$height = empty($img['height']) ? 100 : $img['height'];
$string = (string) isset($_GET['t']) ? $_GET['t'] : $width ."x". $height;

header("Content-Type: image/png");
$image = @imagecreate($width, $height)
    or die(
"Cannot Initialize new GD image stream");

$background_color = imagecolorallocate($image, $background[0], $background[1], $background[2]);
$text_color = imagecolorallocate($image, $color[0], $color[1], $color[2]);

imagestring($image, 5, 5, 5, $string, $text_color);
imagepng($image);
imagedestroy($image);

function
hex2rgb($hex) {
   
// Copied
  
$hex = str_replace("#", "", $hex);

   switch (
strlen($hex)) {
       case
1:
          
$hex = $hex.$hex;
       case
2:
         
$r = hexdec($hex);
         
$g = hexdec($hex);
         
$b = hexdec($hex);
           break;

       case
3:
         
$r = hexdec(substr($hex,0,1).substr($hex,0,1));
         
$g = hexdec(substr($hex,1,1).substr($hex,1,1));
         
$b = hexdec(substr($hex,2,1).substr($hex,2,1));
           break;

       default:
         
$r = hexdec(substr($hex,0,2));
         
$g = hexdec(substr($hex,2,2));
         
$b = hexdec(substr($hex,4,2));
           break;
   }

  
$rgb = array($r, $g, $b);
   return
implode(",", $rgb);
}

官方地址:https://www.php.net/manual/en/image.examples-png.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3