LV. Image 图像函数

简介

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

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

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

需求

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

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

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

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

表格 1. 所支持的图像格式

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

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

表格 2. 所支持的字库

字库下载位置注解
FreeType 1.xhttp://www.freetype.org/ 
FreeType 2http://www.freetype.org/ 
T1libftp://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。

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

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

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

表格 3. 所支持的图像格式

图像格式配置开关
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 库的路径。

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

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

表格 4. 所支持的字库

字库配置开关
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)

范例

例子 1. 用 PHP 创建 PNG 图像

<?php

header
("Content-type: image/png");
$string = $_GET['text'];
$im     = imagecreatefrompng("images/button1.png");
$orange = imagecolorallocate($im, 220, 210, 60);
$px     = (imagesx($im) - 7.5 * strlen($string)) / 2;
imagestring($im, 3, $px, 9, $string, $orange);
imagepng($im);
imagedestroy($im);

?>
本例应该在一个具有类似:<img src="button.php?text=text"> 标记的页面中被调用。上述的 button.php 脚本会取得 "text" 字符串将其覆盖在原图上(本例中的 "images/button1.png")并输出作为结果的图像。用此方法可以很方便地修改按钮上的文字从而避免了每次都要新画一个按钮的图像。用此方法就可以动态生成了。

目录
gd_info -- 取得当前安装的 GD 库的信息
getimagesize -- 取得图像大小
image_type_to_extension -- 取得图像类型的文件后缀
image_type_to_mime_type -- 取得 getimagesize,exif_read_data,exif_thumbnail,exif_imagetype 所返回的图像类型的 MIME 类型
image2wbmp -- 以 WBMP 格式将图像输出到浏览器或文件
imagealphablending -- 设定图像的混色模式
imageantialias -- 是否使用抗锯齿(antialias)功能
imagearc -- 画椭圆弧
imagechar -- 水平地画一个字符
imagecharup -- 垂直地画一个字符
imagecolorallocate -- 为一幅图像分配颜色
imagecolorallocatealpha -- 为一幅图像分配颜色 + alpha
imagecolorat -- 取得某像素的颜色索引值
imagecolorclosest -- 取得与指定的颜色最接近的颜色的索引值
imagecolorclosestalpha -- 取得与指定的颜色加透明度最接近的颜色
imagecolorclosesthwb --  取得与给定颜色最接近的色度的黑白色的索引
imagecolordeallocate -- 取消图像颜色的分配
imagecolorexact -- 取得指定颜色的索引值
imagecolorexactalpha -- 取得指定的颜色加透明度的索引值
imagecolormatch -- 使一个图像中调色板版本的颜色与真彩色版本更能匹配
imagecolorresolve -- 取得指定颜色的索引值或有可能得到的最接近的替代值
imagecolorresolvealpha --  取得指定颜色 + alpha 的索引值或有可能得到的最接近的替代值
imagecolorset -- 给指定调色板索引设定颜色
imagecolorsforindex -- 取得某索引的颜色
imagecolorstotal -- 取得一幅图像的调色板中颜色的数目
imagecolortransparent -- 将某个颜色定义为透明色
imageconvolution -- 用系数 div 和 offset 申请一个 3x3 的卷积矩阵
imagecopy -- 拷贝图像的一部分
imagecopymerge -- 拷贝并合并图像的一部分
imagecopymergegray -- 用灰度拷贝并合并图像的一部分
imagecopyresampled -- 重采样拷贝部分图像并调整大小
imagecopyresized -- 拷贝部分图像并调整大小
imagecreate -- 新建一个基于调色板的图像
imagecreatefromgd2 -- 从 GD2 文件或 URL 新建一图像
imagecreatefromgd2part -- 从给定的 GD2 文件或 URL 中的部分新建一图像
imagecreatefromgd -- 从 GD 文件或 URL 新建一图像
imagecreatefromgif -- 从 GIF 文件或 URL 新建一图像
imagecreatefromjpeg -- 从 JPEG 文件或 URL 新建一图像
imagecreatefrompng -- 从 PNG 文件或 URL 新建一图像
imagecreatefromstring -- 从字符串中的图像流新建一图像
imagecreatefromwbmp -- 从 WBMP 文件或 URL 新建一图像
imagecreatefromxbm -- 从 XBM 文件或 URL 新建一图像
imagecreatefromxpm -- 从 XPM 文件或 URL 新建一图像
imagecreatetruecolor -- 新建一个真彩色图像
imagedashedline -- 画一虚线
imagedestroy -- 销毁一图像
imageellipse -- 画一个椭圆
imagefill -- 区域填充
imagefilledarc -- 画一椭圆弧且填充
imagefilledellipse -- 画一椭圆并填充
imagefilledpolygon -- 画一多边形并填充
imagefilledrectangle -- 画一矩形并填充
imagefilltoborder -- 区域填充到指定颜色的边界为止
imagefilter -- 对图像使用过滤器
imagefontheight -- 取得字体高度
imagefontwidth -- 取得字体宽度
imageftbbox -- 给出一个使用 FreeType 2 字体的文本框
imagefttext -- 使用 FreeType 2 字体将文本写入图像
imagegammacorrect -- 对 GD 图像应用 gamma 修正
imagegd2 -- 将 GD2 图像输出到浏览器或文件
imagegd -- 将 GD 图像输出到浏览器或文件
imagegif -- 以 GIF 格式将图像输出到浏览器或文件
imageinterlace -- 激活或禁止隔行扫描
imageistruecolor -- 检查图像是否为真彩色图像
imagejpeg -- 以 JPEG 格式将图像输出到浏览器或文件
imagelayereffect -- 设定 alpha 混色标志以使用绑定的 libgd 分层效果
imageline -- 画一条线段
imageloadfont -- 载入一新字体
imagepalettecopy -- 将调色板从一幅图像拷贝到另一幅
imagepng -- 以 PNG 格式将图像输出到浏览器或文件
imagepolygon -- 画一个多边形
imagepsbbox -- 给出一个使用 PostScript Type1 字体的文本方框
imagepscopyfont -- 拷贝一个已加载的字体以备更改
imagepsencodefont -- 改变字体中的字符编码矢量
imagepsextendfont -- 扩充或精简字体
imagepsfreefont -- 释放一个 PostScript Type 1 字体所占用的内存
imagepsloadfont -- 从文件中加载一个 PostScript Type 1 字体
imagepsslantfont -- 倾斜某字体
imagepstext -- 用 PostScript Type1 字体把文本字符串画在图像上
imagerectangle -- 画一个矩形
imagerotate -- 用给定角度旋转图像
imagesavealpha -- 设置标记以在保存 PNG 图像时保存完整的 alpha 通道信息(与单一透明色相反)
imagesetbrush -- 设定画线用的画笔图像
imagesetpixel -- 画一个单一像素
imagesetstyle -- 设定画线的风格
imagesetthickness -- 设定画线的宽度
imagesettile -- 设定用于填充的贴图
imagestring -- 水平地画一行字符串
imagestringup -- 垂直地画一行字符串
imagesx -- 取得图像宽度
imagesy -- 取得图像高度
imagetruecolortopalette -- 将真彩色图像转换为调色板图像
imagettfbbox -- 取得使用 TrueType 字体的文本的范围
imagettftext -- 用 TrueType 字体向图像写入文本
imagetypes -- 返回当前 PHP 版本所支持的图像类型
imagewbmp -- 以 WBMP 格式将图像输出到浏览器或文件
imagexbm -- 将 XBM 图像输出到浏览器或文件
iptcembed -- 将二进制 IPTC 数据嵌入到一幅 JPEG 图像中
iptcparse --  将二进制 IPTC http://www.iptc.org/ 块解析为单个标记
jpeg2wbmp -- 将 JPEG 图像文件转换为 WBMP 图像文件
png2wbmp -- 将 PNG 图像文件转换为 WBMP 图像文件

add a note add a note User Contributed Notes
php at synvb dot com
22-Apr-2006 11:19
Here is a single-function to flip, based on the one below.

<?php
 
function flipImage($image, $vertical, $horizontal) {
  
$w = imagesx($image);
  
$h = imagesy($image);

   if (!
$vertical && !$horizontal) return $image;

  
$flipped = imagecreatetruecolor($w, $h);

   if (
$vertical) {
     for (
$y=0; $y<$h; $y++) {
      
imagecopy($flipped, $image, 0, $y, 0, $h - $y - 1, $w, 1);
     }
   }

   if (
$horizontal) {
     if (
$vertical) {
      
$image = $flipped;
      
$flipped = imagecreatetruecolor($w, $h);
     }

     for (
$x=0; $x<$w; $x++) {
      
imagecopy($flipped, $image, $x, 0, $w - $x - 1, 0, 1, $h);
     }
   }

   return
$flipped;
  }
?>
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 )

?>
andrew dot barlow at gmail dot com
01-Mar-2006 01:47
To create a simple transparent gif with black text with any TrueType Font...

Simple put this script into a PHP file and call it with the usual IMG tag.

You can also specify the font size for the IMG tag too.

Change the $font to your own font and upload it to the same directory as this script.

<?php
// Set the content-type
header("Content-type: image/gif");

$fontsize = 18;
if(@
$_GET['fontsize']) {
  
$fontsize = $_GET['fontsize'];
}
$font = 'yourcustomfont.ttf';
$text = @$_GET['text'];

// Create the image
$size = imagettfbbox($fontsize, 0, $font, $text);
$width = $size[2] + $size[0] + 8;
$height = abs($size[1]) + abs($size[7]);

$im = imagecreate($width, $height);

$colourBlack = imagecolorallocate($im, 255, 255, 255);
imagecolortransparent($im, $colourBlack);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// Add the text
imagefttext($im, $fontsize, 0, 0, abs($size[5]), $black, $font, $text);

// Using imagepng() results in clearer text compared with
imagegif($im);
imagedestroy($im);
?>
relsqui at chiliahedron dot com
18-Feb-2006 03:14
<?php
// This is a correction to the image-flipping function I posted previously.
// The bitwise ands (&) were incorrectly written as logical ands (&&).
// Needless to say, that breaks the function in obnoxious--if amusing--ways.

define("VERTICAL", 1);
define("HORIZONTAL", 2);

function
imageflip($image, $mode) {
      
$w = imagesx($image);
      
$h = imagesy($image);
      
$flipped = imagecreate($w, $h);
       if (
$mode & VERTICAL) {
               for (
$y = 0; $y < $h; $y++) {
                      
imagecopy($flipped, $image, 0, $y, 0, $h - $y - 1, $w, 1);
               }
       }
       if (
$mode & HORIZONTAL) {
               for (
$x = 0; $x < $w; $x++) {
                      
imagecopy($flipped, $image, $x, 0, $w - $x - 1, 0, 1, $h);
               }
       }
       return
$flipped;
}
?>
relsqui at chiliahedron dot com
14-Feb-2006 07:22
On the offchance someone else should need one, here's a function you can use to randomly "mix" two colors, resulting in a "child" color with components of both. You might use it to come up with ideas for a color scheme, for example; the image section seemed as good a place for it as any.

<?php
// $mom and $dad should be integers, quite possibly the output of hexdec().
// Similarly, the return value $child will be an integer suitable for feeding to dechex().

breed_colors($mom, $dad) {
       do {
$maskhex .= rand()&1 ? "f" : "0"; } while (strlen($maskhex) < 6);
      
$mask = hexdec($maskhex);
      
$inversemask = $mask ^ 16777215;
      
$child = ($mom & $mask) | ($dad & $inversemask);
       return
$child;
}

// For example:
breed_colors(hexdec("012345"), hexdec("6789ab"));

// Let's say the random mask was ff0f0f.
// The inverse mask is therefore 00f0f0.
// $mom & $mask == 010305.
// $dad & $inversemask == 0080a0.
// Those two |ed together make 0183a5, which combines the traits of the parents into one $child.

?>
jan at anh dot sk
15-Jan-2006 08:03
When outputing an image from a script to a browser, use header("Content-Length: XYZ") together with Content-Type header. This avoids problems rendering-displaying the image with some browsers (f.i. MSIE) - fixes random image cutting of image bottom parts. Image from cache example:

<?php
$cache_file
= "imagecache/{$ID}.img";   

header("Content-Type: image/jpeg");
header("Content-Length: ".filesize($cache_file));

$cache = fopen($cache_file,"r");
fpassthru($cache);
fclose($cache);

exit;
?>

Problem observed @ Linux, Apache 2.0, PHP 4.3.10
matrixhasu at gmail dot com
14-Jan-2006 07:44
Sorry,
a little bug found in the previous note: what was

<?php
for ($i=0; $i<count($Values); $i++){
 
$graphValues[$i] =
 (
$Values[$i] - $min*(1-2*$graphspacing)) *
 ((
$imgHeight*(1-$graphspacing))/($max-$min));
}
?>

now has to be

<?php
for ($i=0; $i<count($Values); $i++){
 
$graphValues[$i] =
 (
$Values[$i] - $min*(1-2*$graphspacing)) *
 ((
$imgHeight*(1-$graphspacing))/($max-$min*(1-2*$graphspacing)));
?>
matrixhasu at gmail dot com
14-Jan-2006 08:02
I've take the example of Peter Hulstaert and modified so:

1. grid width is scaled basing on the number of data points to print;

2. images are scaled by min and max values:
   even if min is 1000, that point will be very close to the image bottom

Hope this will helpfull to someone.

<?
//Original from peter dot hulstaert at gmail dot com
//Available at http://it.php.net/manual/en/ref.image.php#60410
 
header("Content-type: image/png");

// Define variables
$Values=array(120,190,130,155,150,140,320,150,140,186,240,128,650);
$imgWidth=500;
$imgHeight=200;
$grid=25;
$graphspacing=0.07;
//Scales number of vertical grid lines for the number of data to print
$gridW=$imgWidth/(count($Values)-1);

//Get min and max values to scale image
for ($i=0; $i<count($Values); $i++){
  if (
$Values[$i]>$max){$max=$Values[$i];}
}

//Min values are less the maximum...
$min = $max;

for (
$i=0; $i<count($Values); $i++){
  if (
$Values[$i]<$min){$min=$Values[$i];}
}

for (
$i=0; $i<count($Values); $i++){
 
$graphValues[$i] =
 (
$Values[$i] - $min*(1-2*$graphspacing)) *
 ((
$imgHeight*(1-$graphspacing))/($max-$min));
}

// 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/$gridW); $i++)
   {
imageline($image, $i*$gridW, 0, $i*$gridW, $imgHeight, $colorGrey);}
for (
$i=1; $i<($imgHeight/$grid); $i++)
   {
imageline($image, 0, $i*$grid, $imgWidth, $i*$grid, $colorGrey);}

//Create the lines connecting points
for ($i=0; $i<count($graphValues)-1; $i++)
   {
imageline($image, $i*$gridW, ($imgHeight-$graphValues[$i]),
 (
$i+1)*$gridW, ($imgHeight-$graphValues[$i+1]), $colorBlue);}

// Output graph and clear image from memory
imagepng($image);
imagedestroy($image);
?>
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);
?>
razonklnbd at yahoo dot com
26-Dec-2005 03:12
I was looking for a function to get propotional image size. After a bit of thinking I came up with this pretty fast solution:

<?php
function getPropotionalSize($src_w, $src_h, $max_w, $max_h){
  
$return_val['width']=$src_w;
  
$return_val['height']=$src_h;
   if(
$max_w<$src_w || $max_h<$src_h){
      
$return_val['width']=$max_w;
      
$return_val['height']=$max_h;
       if(
$src_w>=$src_h) $return_val['height']=($max_w*$src_h)/$src_w;
       else
$return_val['width']=($max_h*$src_w)/$src_h;
   }
   return
$return_val;
}
?>

Hope it saved somebody some time!
orbitphreak at yahoo dot com
07-Dec-2005 01:46
If you want to have a dynamic image validation code
like yahoo, you can use this function:

<?php
function generateValidationImage($rand) {
   global
$site_font_path;
   global
$site_font_validation;
  
$width = 120;
  
$height = 40;
  
$image = imagecreate($width, $height);
  
$bgColor = imagecolorallocate ($image, 255, 255, 255);
  
$textColor = imagecolorallocate ($image, 0, 0, 0);

  
// Add Random noise
  
for ($i = 0; $i < 250; $i++) {
    
$rx1 = rand(0,$width);
    
$rx2 = rand(0,$width);
    
$ry1 = rand(0,$height);
    
$ry2 = rand(0,$height);
    
$rcVal = rand(0,255);
    
$rc1 = imagecolorallocate($image,
  
rand(0,255),
  
rand(0,255),
  
rand(100,255));

    
imageline ($image, $rx1, $ry1, $rx2, $ry2, $rc1);
   }

  
// write the random number
  
$font = imageloadfont($site_font_path."/".$site_font_validation);
  
imagestring($image, $font, 3, 0, $rand, $textColor);

  
// send several headers to make sure the image is not cached
   // Date in the past

  
header("Expires: Mon, 23 Jul 1993 05:00:00 GMT");

  
// always modified
  
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");

  
// HTTP/1.1
  
header("Cache-Control: no-store, no-cache, must-revalidate");
  
header("Cache-Control: post-check=0, pre-check=0", false);

  
// HTTP/1.0
  
header("Pragma: no-cache");

  
// send the content type header so the image is displayed properly
  
header('Content-type: image/jpeg');

  
imagejpeg($image);
  
imagedestroy($image);
  }

?>

The $site_font_path should be set to something like "/home/user/www/fonts". 
The $site_font_validation should be set to the name of the GD font file,
like "anonymous.gdf". 

You can view and download the code here:
http://www.digital-seven.net/?option=com_content&task=view&id=67
Jonas Sweden
17-Nov-2005 07:51
Simple script for getting a jpg-thumb by submitting imgname and either height or width of the thumb!
<?php
if(isset($_GET["i"]) && ("" != $_GET["i"])){
  
$fn = "path/to/jpgs/".$_GET["i"].".jpg";
   if(
false !== (list($ws,$hs) = @getimagesize($fn))){
       if(isset(
$_GET["w"]) && ("" != $_GET["w"])){
          
$ratio = ((float)$_GET["w"]) / $ws;
           }
       elseif(isset(
$_GET["h"]) && ("" != $_GET["h"])){
          
$ratio = ((float)$_GET["h"]) / $hs;
           }
       if(isset(
$ratio)){
          
$wt = $ws * $ratio;
          
$ht = $hs * $ratio;
          
$thumb = imagecreatetruecolor($wt,$ht);
          
$source = imagecreatefromjpeg($fn);
          
imagecopyresampled($thumb,$source,0,0,0,0,$wt,$ht,$ws,$hs);
          
header('Content-type: image/jpeg');
          
imagejpeg($thumb);
          
imagedestroy($thumb);
           }
       }
   }
?>
skumar2k15 [at] gmail [dot] com
07-Nov-2005 06:24
Generate a line graphs on-the-fly through php image functions.
<br>

code for linechart.php

<?
// Add values to the graph
$graphValues=array(0,80,23,11,190,245,50,80,111,240,55);

// Define .PNG image
header("Content-type: image/png");
$imgWidth=250;
$imgHeight=250;

// 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, 250, $colorGrey);
imageline($image, 0, 0, 250, 0, $colorGrey);
imageline($image, 249, 0, 249, 249, $colorGrey);
imageline($image, 0, 249, 249, 249, $colorGrey);

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

// Create line graph
for ($i=0; $i<10; $i++){
imageline($image, $i*25, (250-$graphValues[$i]), ($i+1)*25, (250-$graphValues[$i+1]), $colorBlue);
}

// Output graph and clear image from memory
imagepng($image);
imagedestroy($image);

?>

Thanks and regards,
skumar k.
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".
trucex at gmail
28-Aug-2005 07:18
@snagnever|gmail|com:

I modified the ascii image script you wrote so that it displays an image that looks real. While impractical due to speed, the concept is actually really cool. Here it is:

<?php
//
// image2asci - test script 2
// by sn4g <snagnever@gmail.com>
// 2005 - april - 2
 
// simple script that read "each" pixel from a image and
// outputs an html colorized version of it.
//
 
$name = basename