 |
LXV. Image 图像函数
PHP 不仅限于只产生 HTML 的输出。还可以创建及操作多种不同图像格式的图像文件,包括
gif,png,jpg,wbmp 和 xpm。更方便的是,PHP
可以直接将图像流输出到浏览器。要处理图像,需要在编译 PHP 时加上图像函数的 GD 库。GD
和 PHP 还可能需要其它的库,视乎需要支持哪些图像格式而定。
可以在 PHP 中使用图像函数来得到
JPEG,GIF,PNG,SWF,TIFF
和 JPEG2000 图像的大小。
注意:
阅读需求一节以了解怎样扩展图像能力来读取,写入和修改图像以及读取数码相机拍摄的照片中的元数据。
如果有 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 了。
注意:
自 PHP 4.3 起绑定了一个 GD
库的版本。这个绑定的版本具有一些附加的特色例如透明混色,应优先使用此版本,因为它的代码维护得更好以及更加稳定。
可能想要增加 GD 处理的图像格式。
可能想要增强 GD 处理不同字体的能力。支持下列字库:
如果 PHP 编译时指定了
--enable-exif,就可以操作存储于
JPEG 和 TIFF
图像文件头中的信息。这样就可以读取上面提到的数码相机生成的照片中的元数据。这些函数不需要
GD 库。
要激活 GD 支持,配置 PHP 时加上
--with-gd[=DIR],DIR 是 GD
的基本安装目录。要使用推荐的绑定的 GD 库版本(首次绑定于 PHP 4.3.0),使用
--with-gd。要编译
GD 库,需要libpng 和 libjpeg。
在 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。
|
以下常量由本扩展模块定义,因此只有在本扩展模块被编译到
PHP 中,或者在运行时被动态加载后才有效。
例 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")并输出作为结果的图像。用此方法可以很方便地修改按钮上的文字从而避免了每次都要新画一个按钮的图像。用此方法就可以动态生成了。
diggertadmin at gmail dot com
24-Jul-2007 04:14
This rather cryptic pair of errors --
"PHP Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 2304 bytes)
Only 0 bytes were written, expected to write 5119 in Unknown"
-- turned out to have a trivial explanation. All it means is that /tmp ran out of free space.
maps at cwsol dot com
22-Apr-2007 07:28
If you are getting the generic error "The image cannot be displayed, because it contains errors.", comment out header("Content-type: image/png");. This will enable PHP to display the real PHP errors.
felipe dot medeiros at kanashii dot com dot br
26-Mar-2007 05:41
Jonathon Reinhart, don't assume it.
.SO and .A files are libraries for dynamic and stactic linking when you compile a program. just to install <package> isn't enought to compile against it's libraries, as them may be only run-time libraries and give you some headache. The correct is to install <package>-devel, which will give you the right libraries for compile time.
And one final word... linux is by now a stable system with lots of working done... if the thing you're trying to do is too hard or unexplained it means that either you're trying something noone ever cared about spending his time on it or you didn't readed how to do it properly. Either way try to learn more about what you're trying.
Jonathon dot Reinhart at DONTSPAMgmail dot com
13-Mar-2007 06:48
I've seen a lot of issues with getting PHP compiled with jpeg and png support. I built it under SuSE 10.2 and ./configure kept giving me "libjpeg.(a|so) not found". I believe that's because my libjpeg was libjpeg.so.62. It also did this for libpng (which mine was named libpng12.so)
Apparently ./config is looking only for the .so files. To resolve this, I installed libjpeg-devel and libpng-devel, which then created symlinks: libpng.so -> libpng12.so and libjpeg.so -> libjpeg.so.62.0.0 . I'm assuming creating these symlinks without installing the -devel packages will work just fine.
Skyeye
19-Aug-2006 10:04
In addition to %0A which you can use for making multiline text images, you can also use underlining and strikethrough.
For underlining use %0D and _, for example:
/image.php?text=Underline.%0D________
For strikethrough use %0D and %E2%80%93, for example:
/image.php?text=Strikethrough.%0D%E2%80%93%E2%80%93%E2%80%93%E2%80%93
%E2%80%93%E2%80%93%E2%80%93%E2%80%93%E2%80%93%E2%80%93
If you want to use both of them in one line you will have to use %20 to dispose the next block of modifying symbols:
/image.php?text=Underline%20and%20Strikethrough.%0D_______%20%20%20%20
%20%20%20%20%20%E2%80%93%E2%80%93%E2%80%93%E2%80%93%E2%80%93%E2%80%93
%E2%80%93%E2%80%93%E2%80%93%E2%80%93
As you see all modifying symbols for whole line are put after %0D in one string after the whole modifyable text and not after each modifyable word. This makes easy to put on and take off modifying string for whole line when it`s necessary.
If the text is on several lines, each line has its own disposition of modifying symbols:
/image.php?text=Underline%20and%0D_______%0AStrikethrough.%0D%E2%80%93
%E2%80%93%E2%80%93%E2%80%93%E2%80%93%E2%80%93%E2%80%93%E2%80%93
%E2%80%93%E2%80%93
Theese are only some examples how to use symbol combining. Using %0D and other symbols from Windows Charmap you can easy make images of characters which even doesn`t exist in any font.
Skyeye
18-Aug-2006 11:43
If you want to make an image through GET with text in several lines, use %0A for line separating, for example:
/image.php?text=Text%20string%0Ain%20several%0Alines.
As also you can make php generated images without other knowing that they are php-made. Simply add the image extension in Apache httpd.conf file:
AddType application/x-httpd-php .php .png
And call image as normal png image:
/somephpautogeneratedimage.png
Of course real .png files will be now treated as php, but if you don`t have png files on your webserver, this won`t be a problem. Or you can use this code for displaying real png images through php code:
<?php
$filename = 'realpngfile.png';
header('Content-type: image/png');
header('Content-length: '.filesize($filename));
readfile($filename);
?>
thomas at tgohome dot com
17-Aug-2006 11:01
I wrote this script to fetch details about a GIF image. I wanted to use it for avatar details on a CMS system, so I wrote it to return an array of details (instead of having to go through all of the functions)
Without further ado, here the script is:
<?
/*
* Get GIF image data
* Returns an array of data, including GIF image type, and
* the width and height of the image, plus transparent colour
* details and much more.
*
* Copyright 2006 Thomas Oldbury.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
/*
* This function takes one argument, $file, a direct link to the image in
* question. Perhaps in future versions it will get the file from an image
* resource, but for now, it will have to do.
*/
function fetch_gif_data($file) {
/*
* First, we need to get the contents of the file in question, or we print
* a warning using trigger_error().
*/
$file_data = @file_get_contents($file) or trigger_error("File $file does not exist", E_USER_WARNING);
/*
* Now we need to fetch the gif image's version. We'll use strpos to fetch
* gif89a, gif87a or if we don't get that then we will print an error.
*/
$image_type = strpos($file_data, "g");
/*
* Now we check to see wether it is actually a GIF image, as it may not be
* an image and if this is the case, problems could occur.
*/
if($image_type === false) {
trigger_error("File $file is not a gif89a or gif87a compatible image", E_USER_ERROR);
}
/*
* Now, we need to fetch the image type by fetching the text at a certain
* position, using PHP's function substr.
*/
$image_info[version] = substr($file_data, 0, 6);
$image_info[file_reg_version] = substr($file_data, 3, 3);
/*
* Let's get the total number of colours in this image using a special
* piece of code, which fetches all the image's colours.
*/
$im_gif = imagecreatefromgif($file);
$image_info[total_pallete_colours] = imagecolorstotal($im_gif);
/*
* Now, the next thing we need to do is get the width and height of the
* image in question by using imagesx(); and imagesy();
*/
$image_info[width] = imagesx($im_gif);
$image_info[height] = imagesy($im_gif);
/*
* Let's fetch the transparent color of the image, if there is one.
*/
$id = imagecolortransparent($im_gif);
$image_info[transparent_color_id] = $id;
$image_info[transparent_color_values] = imagecolorsforindex($im_gif, $id);
/*
* Now, we return all the data.
*/
return $image_info;
}
/*
* Usage Example:
*/
echo '<pre>';
print_r(fetch_gif_data("hello.gif"));
echo '</pre>';
?>
This script returns something like:
Array
(
[version] => GIF89a
[file_reg_version] => 89a
[total_pallete_colours] => 251
[width] => 100
[height] => 100
[transparent_color_id] => 16
[transparent_color_values] => Array
(
[red] => 0
[green] => 0
[blue] => 0
[alpha] => 127
)
)
Tested on PHP 5.1.2, but should work on older versions.
sampathperera at hotmail dot com - Sri Lanka
21-Jul-2006 05:04
I have used following function to generate Security Images to authenticate users are real humans. Need to have GD graphic library with FreeType enabled.
Used a gif file as background, put random text on it & creates a new gif file as output.
<?php
function createImage(){
// creates the images, writes the file
$fileRand = md5(rand(100000,999999));
$string_a = array("A","B","C","D","E","F","G","H","J","K",
"L","M","N","P","R","S","T","U","V","W","X","Y","Z",
"2","3","4","5","6","7","8","9");
$keys = array_rand($string_a, 6);
foreach($keys as $n=>$v){
$string .= $string_a[$v];
}
$backgroundimage = "security_background.gif";
$im=imagecreatefromgif($backgroundimage);
$colour = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
$font = 'Arial';
$angle = rand(-5,5);
// Add the text
imagettftext($im, 16, $angle, 15, 25, $colour, $font, $string);
$outfile= "$fileRand.gif";
imagegif($im,$outfile);
return $outfile;
}
echo "<IMG SRC=".createImage()." name=secimg>";
?>
g8z at yahoo dot com
19-Jul-2006 08:39
<?php
/**
chunk_image breaks an image into roughly equal chunks horizontally (which are returned in an array of image resources)
parameters:
$image = image resource to work on
$chunks = number of chunks to break the image into
Courtesy of the $5 Script Achive: http://www.tufat.com
**/
function chunk_image_horizontally ($image, $chunks = 1)
{
$image_width = imagesx($image);
$image_height = imagesy($image);
// calculate required chunk size
$chunk_size = round($image_width / $chunks);
// do all but the last chunk
for ($current_chunk = 1; $current_chunk < $chunks; $current_chunk++) {
// create image resource to store chunk
$chunk_images[$current_chunk - 1] = imagecreate($chunk_size, $image_height);
// copy chunk to chunk images array
imagecopy($chunk_images[$current_chunk - 1], $image, 1, 1, $chunk_size * ($current_chunk - 1) + 1 , 1, $chunk_size, $image_height);
}
// get last chunk
$chunk_images[$chunks - 1] = imagecreate($chunk_size, $image_height);
imagecopy($chunk_images[$chunks - 1], $image, 1, 1, $chunk_size * ($chunks - 1) + 1 , 1, $image_width, $image_height);
// return array
return $chunk_images;
}
//Example:
// read in test.jpg, and break it into 4 chunks using our function
$in_image = imagecreatefromjpeg('./image.jpg');
$images = chunk_image_horizontally($in_image, 4);
$count = 0;
// save chunks to files
foreach ($images as $image) {
$count++;
imagejpeg($image, './test_chunk'.$count.'.jpg');
}
?>
g8z at yahoo dot com
19-Jul-2006 08:36
<?php
/**
change_color replaces $old_color with $new_color. $threshold allows you to specify how far away from the specified color a pixel can be and still be considered a match. $old_color and $new_color must be decimal color values.
Courtesy of the $5 Script Achive: http://www.tufat.com
*/
function change_color($image, $old_color, $new_color, $threshold = 15)
{
$image_width = imagesx($image);
$image_height = imagesy($image);
// iterate through x axis
for ($x = 0; $x < $image_width; $x++) {
// iterate through y axis
for ($y = 0; $y < $image_height; $y++) {
// look at current pixel
$pixel_color = imagecolorat($image, $x, $y);
if (($pixel_color <= $old_color + $threshold) && ($pixel_color >= $old_color - $threshold)) {
// replace with new color
imagesetpixel($image, $x, $y, $new_color);
}
}
}
}
// EXAMPLE:
// convert all red in the image to green
$image = imagecreatefromjpeg('./test.jpg');
$red_rbg = 16646146;
$green_rbg = 65341;
change_color($image, $red_rbg, $green_rbg, 15);
imagejpeg($image, './test_changed.jpg');
?>
php at synvb dot com
22-Apr-2006 03: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 12: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 05: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
28-Feb-2006 05: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
17-Feb-2006 07: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 11: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 12: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 11: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 12: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 01: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(
|