PHP
downloads | documentation | faq | getting help | mailing lists | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

gd_info> <iis_stop_service
Last updated: Sun, 25 Nov 2007

view this page in

Image 图像函数

简介

PHP 不仅限于只产生 HTML 的输出。还可以创建及操作多种不同图像格式的图像文件,包括 gif,png,jpg,wbmp 和 xpm。更方便的是,PHP 可以直接将图像流输出到浏览器。要处理图像,需要在编译 PHP 时加上图像函数的 GD 库。GD 和 PHP 还可能需要其它的库,视乎需要支持哪些图像格式而定。

可以在 PHP 中使用图像函数来得到 JPEGGIFPNGSWFTIFFJPEG2000 图像的大小。

Note: 阅读需求一节以了解怎样扩展图像能力来读取,写入和修改图像以及读取数码相机拍摄的照片中的元数据。

需求

如果有 GD 库(在 » http://www.libgd.org/),可以创建及操作图像。

所能处理的图像格式取决于所安装的 GD 版本,以及其它 GD 可能用到的来访问这些图像格式的库。低于 gd-1.6 版本的 GD 支持 GIF 图像格式,不支持 PNG,高于 gd-1.6 低于 gd-2.0.28 的版本支持 PNG,不支持 GIF。在 gd-2.0.28 中又重新支持 GIF 了。

Note: 自 PHP 4.3 起绑定了一个 GD 库的版本。这个绑定的版本具有一些附加的特色例如透明混色,应优先使用此版本,因为它的代码维护得更好以及更加稳定。

可能想要增加 GD 处理的图像格式。

所支持的图像格式
图像格式 要下载的库 注解
gif   仅在低于 gd-1.6 与高于 gd-2.0.28 的 GD 版本中支持。PHP 4.3.0 以及绑定的 GD 库中支持只读的 GIF。PHP 4.3.9 和 PHP 5.0.1 起支持写入
jpeg-6b » ftp://ftp.uu.net/graphics/jpeg/  
png » http://www.libpng.org/pub/png/libpng.html 仅在高于 gd-1.6 的 GD 版本中支持。
xpm » ftp://metalab.unc.edu/pub/Linux/libs/X/!INDEX.html 如果系统中安装了 X 环境,则很可能已经有了这个库。

可能想要增强 GD 处理不同字体的能力。支持下列字库:

所支持的字库
字库 下载位置 注解
FreeType 1.x » http://www.freetype.org/  
FreeType 2 » http://www.freetype.org/  
T1lib » ftp://sunsite.unc.edu/pub/Linux/libs/graphics/) 支持 Type 1 字体。

如果 PHP 编译时指定了 --enable-exif,就可以操作存储于 JPEGTIFF 图像文件头中的信息。这样就可以读取上面提到的数码相机生成的照片中的元数据。这些函数不需要 GD 库。

安装

要激活 GD 支持,配置 PHP 时加上 --with-gd[=DIR],DIR 是 GD 的基本安装目录。要使用推荐的绑定的 GD 库版本(首次绑定于 PHP 4.3.0),使用 --with-gd。要编译 GD 库,需要libpnglibjpeg

在 Windows 中,需要将 GD2 的 DLL 文件 php_gd2.dll 作为一个扩展包含在 php.ini 中。GD1 的 DLL 文件 php_gd.dll 在 PHP 4.3.2 中被删除了。此外要注意首选的真彩色图像函数,例如 imagecreatetruecolor(),需要 GD2。

Note: 要在 Windows 下启用 exif,在 php.ini 中 php_mbstring.dll 必须在 php_exif.dll 之前加载。

要在 PHP 3 中禁止 GD 支持,在配置时加上 --without-gd

要增强 GD 的能力以处理更多的图像格式,在配置 PHP 时指定 --with-XXXX 的配置开关。

所支持的图像格式
图像格式 配置开关
jpeg-6b 要激活 jpeg-6b 的支持,加上 --with-jpeg-dir=DIR.
png 要激活 png 的支持,加上 --with-png-dir=DIR。注意,libpng 需要 zlib library,因此配置中还要加上 --with-zlib-dir[=DIR]
xpm 要激活 xpm 的支持,加上 --with-xpm-dir=DIR。如果配置时提示找不到所需要的库,可以加上到 X11 库的路径。

Note: 当把 PHP 和 libpng 一起编译时,必须使用和 GD 库连接的同一个版本。

要增强 GD 的能力以处理更多的字体,在配置 PHP 时指定 --with-XXXX 的配置开关。

所支持的字库
字库 配置开关
FreeType 1.x 要激活 FreeType 1.x 的支持,加上 --with-ttf[=DIR]
FreeType 2 要激活 FreeType 2 的支持,加上 --with-freetype-dir=DIR
T1lib 要激活 T1lib(Type 1 字体),加上 --with-t1lib[=DIR]
本地 TrueType 字符串函数 要激活本地 TrueType 字符串函数的支持,加上 --enable-gd-native-ttf

运行时配置

没有 image 特定的配置选项。不过可以参考 exif 扩展库配置指令。

资源类型

本扩展模块未定义任何资源类型。

预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

IMG_GIF (integer)
IMG_JPG (integer)
IMG_JPEG (integer)
IMG_PNG (integer)
IMG_WBMP (integer)
IMG_XPM (integer)
IMG_COLOR_TILED (integer)
IMG_COLOR_STYLED (integer)
IMG_COLOR_BRUSHED (integer)
IMG_COLOR_STYLEDBRUSHED (integer)
IMG_COLOR_TRANSPARENT (integer)
IMG_ARC_ROUNDED (integer)
IMG_ARC_PIE (integer)
IMG_ARC_CHORD (integer)
IMG_ARC_NOFILL (integer)
IMG_ARC_EDGED (integer)
IMAGETYPE_GIF (integer)
IMAGETYPE_JPEG (integer)
IMAGETYPE_PNG (integer)
IMAGETYPE_SWF (integer)
IMAGETYPE_PSD (integer)
IMAGETYPE_BMP (integer)
IMAGETYPE_WBMP (integer)
IMAGETYPE_XBM (integer)
IMAGETYPE_TIFF_II (integer)
IMAGETYPE_TIFF_MM (integer)
IMAGETYPE_IFF (integer)
IMAGETYPE_JB2 (integer)
IMAGETYPE_JPC (integer)
IMAGETYPE_JP2 (integer)
IMAGETYPE_JPX (integer)
IMAGETYPE_SWC (integer)

范例

Example#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")并输出作为结果的图像。用此方法可以很方便地修改按钮上的文字从而避免了每次都要新画一个按钮的图像。用此方法就可以动态生成了。

Table of Contents



gd_info> <iis_stop_service
Last updated: Sun, 25 Nov 2007
 
add a note add a note User Contributed Notes
Image
dev at kingthief dot com
29-Mar-2008 12:20
I've developed a well-documented, fairly rock-solid API for creating on the fly, anti-aliased, rounded corner images, including full alpha transparency support for all you PNG lovers.

go here to download the package:
http://sourceforge.net/projects/roundedphp/

go here for a live demo:
http://dev.kingthief.com/demos/roundedphp/

Installation is similar to PEAR.

Enjoy!
ph_corp at yahoo dot fr
23-Dec-2007 07:19
<?php

/**
HSL/RGB conversion functions
very useful for a lot of applications
**/

function RBGtoHSL ( $R, $G, $B )
{

   
$var_R = ( $R / 255 );
   
$var_G = ( $G / 255 );
   
$var_B = ( $B / 255 );

   
$var_Min = min( $var_R, $var_G, $var_B )
   
$var_Max = max( $var_R, $var_G, $var_B )
   
$del_Max = $var_Max - $var_Min

    $L
= ( $var_Max + $var_Min ) / 2;

    if (
$del_Max == 0 )
    {
      
$H = 0
       $S
= 0
   
}
    else
    {
        if (
$L < 0.5 )
        {
           
$S = $del_Max / ( $var_Max + $var_Min );
        }
        else
        {
           
$S = $del_Max / ( 2 - $var_Max - $var_Min );
        }

       
$del_R = ( ( ( $var_Max - $var_R ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
       
$del_G = ( ( ( $var_Max - $var_G ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
       
$del_B = ( ( ( $var_Max - $var_B ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;

        if (
$var_R == $var_Max )
        {
           
$H = $del_B - $del_G;
        }
        else if (
$var_G == $var_Max )
        {
           
$H = ( 1 / 3 ) + $del_R - $del_B;
        }
        else if (
$var_B == $var_Max )
        {
           
$H = ( 2 / 3 ) + $del_G - $del_R;
        }

        if (
$H < 0 )
        {
           
$H += 1;
        }
        if (
$H > 1 )
        {
           
$H -= 1
       
}

    }

    return array(
$H, $S, $L );

}

function
HuetoRGB( $v1, $v2, $vH )
{
    if (
$vH < 0 )
    {
       
$vH += 1;
    }
    if (
$vH > 1 )
    {
       
$vH -= 1;
    }
    if ( (
6 * $vH ) < 1 )
    {
        return (
$v1 + ( $v2 - $v1 ) * 6 * $vH );
    }
    if ( (
2 * $vH ) < 1 )
    {
        return (
$v2 );
    }
    if ( (
3 * $vH ) < 2 )
    {
        return (
$v1 + ( $v2 - $v1 ) * ( ( 2 / 3 ) - $vH ) * 6 );
    }
    return (
$v1 )
}

function
HSLtoRGB ( $H, $S, $L )
{

    if (
$S == 0 )
    {
       
$R = $L * 255;
       
$G = $L * 255;
       
$B = $L * 255;
    }
    else
    {
        if (
$L < 0.5 )
        {
           
$var_2 = $L * ( 1 + $S );
        }
        else
        {
           
$var_2 = ( $L + $S ) - ( $S * $L );
        }

       
$var_1 = 2 * $L - $var_2;

       
$R = 255 * HuetoRGB( $var_1, $var_2, $H + ( 1 / 3 ) );
       
$G = 255 * HuetoRGB( $var_1, $var_2, $H );
       
$B = 255 * HuetoRGB( $var_1, $var_2, $H - ( 1 / 3 ) );
    }

    return array(
$R, $G, $B );

}

function
distance ( $R1, $G1, $B1, $R2, $G2, $B2 )
{
   
$result = sqrt ( ( $R1 - $R2 )*( $R1 - $R2 ) + ( $G1 - $G2 )*( $G1 - $G2 ) + ( $B1 - $B2 )*( $B1 - $B2 ) );
    return (
$result );
}

?>
shd at earthling dot net
28-Mar-2006 08:44
If you happen to need a way to output a Windows BMP file (e.g. when using the PEAR ExcelWriter), feel free to use the following code:

<?php
function imagebmp ($im, $fn = false)
{
    if (!
$im) return false;
           
    if (
$fn === false) $fn = 'php://output';
   
$f = fopen ($fn, "w");
    if (!
$f) return false;
           
   
//Image dimensions
   
$biWidth = imagesx ($im);
   
$biHeight = imagesy ($im);
   
$biBPLine = $biWidth * 3;
   
$biStride = ($biBPLine + 3) & ~3;
   
$biSizeImage = $biStride * $biHeight;
   
$bfOffBits = 54;
   
$bfSize = $bfOffBits + $biSizeImage;
           
   
//BITMAPFILEHEADER
   
fwrite ($f, 'BM', 2);
   
fwrite ($f, pack ('VvvV', $bfSize, 0, 0, $bfOffBits));
           
   
//BITMAPINFO (BITMAPINFOHEADER)
   
fwrite ($f, pack ('VVVvvVVVVVV', 40, $biWidth, $biHeight, 1, 24, 0, $biSizeImage, 0, 0, 0, 0));
           
   
$numpad = $biStride - $biBPLine;
    for (
$y = $biHeight - 1; $y >= 0; --$y)
    {
        for (
$x = 0; $x < $biWidth; ++$x)
        {
           
$col = imagecolorat ($im, $x, $y);
           
fwrite ($f, pack ('V', $col), 3);
        }
        for (
$i = 0; $i < $numpad; ++$i)
           
fwrite ($f, pack ('C', 0));
    }
   
fclose ($f);
    return
true;
}
?>

It works the same way as regular imagejpeg/imagepng do and only supports GD2.0 true colour bitmaps (which is what's required by ExcelWriter).
felipensp at gmail dot com
13-Mar-2006 01:17
Representation decimal of a color in hexadecimal for use on functions of library GD.

<?php

   
// Representation hexadecimal
   
$var = '#FFFFFF';

    function
getRgbFromGd($color_hex) {

        return
array_map('hexdec', explode('|', wordwrap(substr($color_hex, 1), 2, '|', 1)));

    }
   
   
print_r(getRgbFromGd($var));

   
// Output: Array ( [0] => 255 [1] => 255 [2] => 255 )

?>
peter dot hulstaert at gmail dot com
06-Jan-2006 09:18
While I was searching for a good way to draw a graph, I stumbled on skumar2k15's script.

I have taken the liberty to improve multiple aspects of it.

1. The array can grow and shrink in size, the graph will adjust accordingly.
2. All the values in the array are recalculated so they won't get bigger than the height of the graph.
3. I inserted the possibility to keep a percentage off the height away from the edge.
4. You can adjust the size of the grid.
5. Everything will adjust when you change the height of width.

<?
header
("Content-type: image/png");

// Define variables
$Values=array(50,90,30,155,50,40,320,50,40,86,240,128,650,540,320);
$imgWidth=500;
$imgHeight=200;
$grid=25;
$graphspacing=0.05;

//Creation of new array with hight adjusted values
while (list($key, $val) = each($Values))
    {if(
$val>$max){$max=$val;}}

for (
$i=0; $i<count($Values); $i++){
$graphValues[$i] = $Values[$i] * (($imgHeight*(1-$graphspacing))/$max);
}
// Create image and define colors

$image=imagecreate($imgWidth, $imgHeight);
$colorWhite=imagecolorallocate($image, 255, 255, 255);
$colorGrey=imagecolorallocate($image, 192, 192, 192);
$colorBlue=imagecolorallocate($image, 0, 0, 255);

// Create border around image
imageline($image, 0, 0, 0, $imgHeight, $colorGrey);
imageline($image, 0, 0, $imgWidth, 0, $colorGrey);
imageline($image, $imgWidth-1, 0, $imgWidth-1, $imgHeight-1, $colorGrey);
imageline($image, 0, $imgHeight-1, $imgWidth-1, $imgHeight-1, $colorGrey);

// Create grid
for ($i=1; $i<($imgWidth/$grid); $i++)
    {
imageline($image, $i*$grid, 0, $i*$grid, $imgHeight, $colorGrey);}
for (
$i=1; $i<($imgHeight/$grid); $i++)
    {
imageline($image, 0, $i*$grid, $imgWidth, $i*$grid, $colorGrey);}

// Create line graph
if($imgWidth/$grid>count($graphValues)){$space=$grid;}
else{
$space = $imgWidth/(count($graphValues)-1);}

for (
$i=0; $i<count($graphValues)-1; $i++)
    {
imageline($image, $i*$space, ($imgHeight-$graphValues[$i]), ($i+1)*$space, ($imgHeight-$graphValues[$i+1]), $colorBlue);}

// Output graph and clear image from memory
imagepng($image);
imagedestroy($image);
?>
michal-ok at o2 dot pl
19-Oct-2005 05:29
The image sharpen function (by Alex R. Austin) provided below seems to be very resource hungry and I couldn't make it work on two different servers - trying to sharpen a 413 x 413 image I ended up with "Fatal error: Allowed memory size of 8388608 bytes exhausted" or "Internal Server Error" or the script terminated without notice. Because I had no priviliges to change the default memory limit on these servers I started looking for other sharpen functions. I have come across a php Unsharp Mask function which works like a charm on both of the servers I dealt with. It can be found at http://vikjavev.no/hovudsida/umtestside.php.
mslemko
10-Oct-2005 03:09
For fedora core 4 users that find that the gd library isn't installed, you can issue the command (as root)

# yum install php-gd

it should download and install the gd library. You will need to restart apache... phpinfo() should then tell you "GD Support     enabled".
timeshifting at gmail dot com
25-Aug-2005 06:39
To sharpen an image, rather than using the code below that produces a sharpening filter with php, use the built-in GD function "imageconvolution" which is designed for this purpose. Matrices can be used for sharpening, blurring, edge detection, etc, ala Photoshop.

A sharpening example:

<?php

$sharpenMatrix
= array(-1,-1,-1,-1,16,-1,-1,-1,-1);
$divisor = 8;
$offset = 0;

imageconvolution($myImage, $sharpenMatrix, $divisor, $offset);

?>

Below is some information on building different kinds of matrices. (If you have photoshop (or PSP, GIMP) you can test out your matrices before applying them in PHP)

http://loriweb.pair.com/8udf-basics.html (covers blurs)
http://loriweb.pair.com/8udf-sharpen.html
http://loriweb.pair.com/8udf-edges.html
http://loriweb.pair.com/8udf-emboss.html
jeff at lushmedia dot com
05-Nov-2003 12:52
I wrote an online overview of the image functions that people might find useful. In addition to a general overview of the various function categories and code samples, I have included many interactive examples of the functions, allowing viewers to experiment with the parameters, and seeing the results in real time. The presentation is located at New York PHP
http://www.nyphp.org/content/presentations/GDintro/
sellout at NoSpAm dot dharmadevil dot com
17-Apr-2003 01:06
A fun little function to output UPC-A 11-digit barcodes.
Thanks to barcodeisland.com for the specs.

<?php

function UPCAbarcode($code) {
 
$lw = 2; $hi = 100;
 
$Lencode = array('0001101','0011001','0010011','0111101','0100011',
                  
'0110001','0101111','0111011','0110111','0001011');
 
$Rencode = array('1110010','1100110','1101100','1000010','1011100',
                  
'1001110','1010000','1000100','1001000','1110100');
 
$ends = '101'; $center = '01010';
 
/* UPC-A Must be 11 digits, we compute the checksum. */
 
if ( strlen($code) != 11 ) { die("UPC-A Must be 11 digits."); }
 
/* Compute the EAN-13 Checksum digit */
 
$ncode = '0'.$code;
 
$even = 0; $odd = 0;
  for (
$x=0;$x<12;$x++) {
    if (
$x % 2) { $odd += $ncode[$x]; } else { $even += $ncode[$x]; }
  }
 
$code.=(10 - (($odd * 3 + $even) % 10)) % 10;
 
/* Create the bar encoding using a binary string */
 
$bars=$ends;
 
$bars.=$Lencode[$code[0]];
  for(
$x=1;$x<6;$x++) {
   
$bars.=$Lencode[$code[$x]];
  }
 
$bars.=$center;
  for(
$x=6;$x<12;$x++) {
   
$bars.=$Rencode[$code[$x]];
  }
 
$bars.=$ends;
 
/* Generate the Barcode Image */
 
$img = ImageCreate($lw*95+30,$hi+30);
 
$fg = ImageColorAllocate($img, 0, 0, 0);
 
$bg = ImageColorAllocate($img, 255, 255, 255);
 
ImageFilledRectangle($img, 0, 0, $lw*95+30, $hi+30, $bg);
 
$shift=10;
  for (
$x=0;$x<strlen($bars);$x++) {
    if ((
$x<10) || ($x>=45 && $x<50) || ($x >=85)) { $sh=10; } else { $sh=0; }
    if (
$bars[$x] == '1') { $color = $fg; } else { $color = $bg; }
   
ImageFilledRectangle($img, ($x*$lw)+15,5,($x+1)*$lw+14,$hi+5+$sh,$color);
  }
 
/* Add the Human Readable Label */
 
ImageString($img,4,5,$hi-5,$code[0],$fg);
  for (
$x=0;$x<5;$x++) {
   
ImageString($img,5,$lw*(13+$x*6)+15,$hi+5,$code[$x+1],$fg);
   
ImageString($img,5,$lw*(53+$x*6)+15,$hi+5,$code[$x+6],$fg);
  }
 
ImageString($img,4,$lw*95+17,$hi-5,$code[11],$fg);
 
/* Output the Header and Content. */
 
header("Content-Type: image/png");
 
ImagePNG($img);
}

UPCAbarcode('12345678901');

?>

gd_info> <iis_stop_service
Last updated: Sun, 25 Nov 2007
 
 
show source | credits | sitemap | contact | advertising | mirror sites