PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<ob_iconv_handlerexif_imagetype>
view the version of this page
Last updated: Thu, 21 Aug 2003

XL. Image functions

Introduction

PHP is not limited to creating just HTML output. It can also be used to create and manipulate image files in a variety of different image formats, including gif, png, jpg, wbmp, and xpm. Even more convenient, PHP can output image streams directly to a browser. You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.

You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images.

Note: Read requirements section about how to expand image capabilities to read, write and modify images and to read meta data of pictures taken by digital cameras.

Requirements

If you have the GD library (available at http://www.boutell.com/gd/) you will also be able to create and manipulate images.

The format of images you are able to manipulate depend on the version of GD you install, and any other libraries GD might need to access those image formats. Versions of GD older than gd-1.6 support GIF format images, and do not support PNG, where versions greater than gd-1.6 support PNG, not GIF.

Note: Since PHP 4.3 there is a bundled version of the GD lib. This bundled version has some additional features like alpha blending, and should be used in preference to the external library since it's codebase is better maintained and more stable.

You may wish to enhance GD to handle more image formats.

Table 1. Supported image formats

Image formatLibrary to downloadNotes
gif  Only supported in GD versions older than gd-1.6. Read-only GIF support is available with PHP 4.3.0 and the bundled GD-library.
jpeg-6bftp://ftp.uu.net/graphics/jpeg/ 
pnghttp://www.libpng.org/pub/png/libpng.html Only supported in GD versions greater than gd-1.6.
xpmftp://metalab.unc.edu/pub/Linux/libs/X/!INDEX.html It's likely you have this library already available, if your system has an installed X-Environment.

You may wish to enhance GD to deal with different fonts. The following font libraries are supported:

Table 2. Supported font libraries

Font libraryDownloadNotes
FreeType 1.xhttp://www.freetype.org/ 
FreeType 2http://www.freetype.org/ 
T1libftp://sunsite.unc.edu/pub/Linux/libs/graphics/) Support for Type 1 fonts.

If you have PHP compiled with --enable-exif you are able to work with information stored in headers of JPEG and TIFF images. This way you can read meta data generated by digital cameras as mentioned above. These functions does not require the GD library.

Note: PHP does not require any additional library for the exif module.

Installation

To enable GD-support configure PHP --with-gd[=DIR], where DIR is the GD base install directory. To use the recommended bundled version of the GD library (which was first bundled in PHP 4.3.0), use the configure option --with-gd. In Windows, you'll include the GD2 DLL php_gd2.dll as an extension in php.ini. The GD1 DLL php_gd.dll was removed in PHP 4.3.2. Also note that the preferred truecolor image functions, such as imagecreatetruecolor(), require GD2.

To disable GD support in PHP 3 add --without-gd to your configure line.

Enhance the capabilities of GD to handle more image formats by specifying the --with-XXXX configure switch to your PHP configure line.

Table 3. Supported image formats

Image FormatConfigure Switch
jpeg-6b To enable support for jpeg-6b add --with-jpeg-dir=DIR.
png To enable support for png add --with-png-dir=DIR. Note, libpng requires the zlib library, therefore add --with-zlib-dir[=DIR] to your configure line.
xpm To enable support for xpm add --with-xpm-dir=DIR. If configure is not able to find the required libraries, you may add the path to your X11 libraries.

Enhance the capabilities of GD to deal with different fonts by specifying the --with-XXXX configure switch to your PHP configure line.

Table 4. Supported font libraries

Font libraryConfigure Switch
FreeType 1.x To enable support for FreeType 1.x add --with-ttf[=DIR].
FreeType 2 To enable support for FreeType 2 add --with-freetype-dir=DIR.
T1lib To enable support for T1lib (Type 1 fonts) add --with-t1lib[=DIR].
Native TrueType string function To enable support for native TrueType string function add --enable-gd-native-ttf.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Exif supports automatically conversion for Unicode and JIS character encodings of user comments when module mbstring is available. This is done by first decoding the comment using the specified characterset. The result is then encoded with another characterset which should match your HTTP output.

Table 5. Exif configuration options

NameDefaultChangeable
exif.encode_unicode"ISO-8859-15"PHP_INI_ALL
exif.decode_unicode_motorola"UCS-2BE"PHP_INI_ALL
exif.decode_unicode_intel"UCS-2LE"PHP_INI_ALL
exif.encode_jis""PHP_INI_ALL
exif.decode_jis_motorola"JIS"PHP_INI_ALL
exif.decode_jis_intel"JIS"PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here's a short explanation of the configuration directives.

exif.encode_unicode string

exif.encode_unicode defines the characterset UNICODE user comments are handled. This defaults to ISO-8859-15 which should work for most non asian countries. The setting can be empty or must be an encoding supported by mbstring. If it is empty the current internal encoding of mbstring is used.

exif.decode_unicode_motorola string

exif.decode_unicode_motorola defines the image internal characterset for Unicode encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2BE.

exif.decode_unicode_intel string

exif.decode_unicode_intel defines the image internal characterset for Unicode encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2LE.

exif.encode_jis string

exif.encode_jis defines the characterset JIS user comments are handled. This defaults to an empty value which forces the functions to use the current internal encoding of mbstring.

exif.decode_jis_motorola string

exif.decode_jis_motorola defines the image internal characterset for JIS encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.

exif.decode_jis_intel string

exif.decode_jis_intel defines the image internal characterset for JIS encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.

Resource Types

This extension has no resource types defined.

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

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)

Examples

Example 1. PNG creation with PHP

<?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);
?>
This example would be called from a page with a tag like: <img src="button.php?text=text">. The above button.php script then takes this "text" string and overlays it on top of a base image which in this case is "images/button1.png" and outputs the resulting image. This is a very convenient way to avoid having to draw new button images every time you want to change the text of a button. With this method they are dynamically generated.

Table of Contents
exif_imagetype -- Determine the type of an image
exif_read_data -- Reads the EXIF headers from JPEG or TIFF. This way you can read meta data generated by digital cameras.
exif_thumbnail -- Retrieve the embedded thumbnail of a TIFF or JPEG image
gd_info -- Retrieve information about the currently installed GD library
getimagesize -- Get the size of an image
image_type_to_mime_type -- Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
image2wbmp -- Output image to browser or file
imagealphablending -- Set the blending mode for an image
imageantialias --  Should antialias functions be used or not
imagearc -- Draw a partial ellipse
imagechar -- Draw a character horizontally
imagecharup -- Draw a character vertically
imagecolorallocate -- Allocate a color for an image
imagecolorallocatealpha -- Allocate a color for an image
imagecolorat -- Get the index of the color of a pixel
imagecolorclosest -- Get the index of the closest color to the specified color
imagecolorclosestalpha -- Get the index of the closest color to the specified color + alpha
imagecolorclosesthwb --  Get the index of the color which has the hue, white and blackness nearest to the given color
imagecolordeallocate -- De-allocate a color for an image
imagecolorexact -- Get the index of the specified color
imagecolorexactalpha -- Get the index of the specified color + alpha
imagecolormatch --  Makes the colors of the palette version of an image more closely match the true color version
imagecolorresolve --  Get the index of the specified color or its closest possible alternative
imagecolorresolvealpha --  Get the index of the specified color + alpha or its closest possible alternative
imagecolorset -- Set the color for the specified palette index
imagecolorsforindex -- Get the colors for an index
imagecolorstotal -- Find out the number of colors in an image's palette
imagecolortransparent -- Define a color as transparent
imagecopy -- Copy part of an image
imagecopymerge -- Copy and merge part of an image
imagecopymergegray -- Copy and merge part of an image with gray scale
imagecopyresampled -- Copy and resize part of an image with resampling
imagecopyresized -- Copy and resize part of an image
imagecreate -- Create a new palette based image
imagecreatefromgd2 -- Create a new image from GD2 file or URL
imagecreatefromgd2part -- Create a new image from a given part of GD2 file or URL
imagecreatefromgd -- Create a new image from GD file or URL
imagecreatefromgif -- Create a new image from file or URL
imagecreatefromjpeg -- Create a new image from file or URL
imagecreatefrompng -- Create a new image from file or URL
imagecreatefromstring -- Create a new image from the image stream in the string
imagecreatefromwbmp -- Create a new image from file or URL
imagecreatefromxbm -- Create a new image from file or URL
imagecreatefromxpm -- Create a new image from file or URL
imagecreatetruecolor -- Create a new true color image
imagedashedline -- Draw a dashed line
imagedestroy -- Destroy an image
imageellipse -- Draw an ellipse
imagefill -- Flood fill
imagefilledarc -- Draw a partial ellipse and fill it
imagefilledellipse -- Draw a filled ellipse
imagefilledpolygon -- Draw a filled polygon
imagefilledrectangle -- Draw a filled rectangle
imagefilltoborder -- Flood fill to specific color
imagefontheight -- Get font height
imagefontwidth -- Get font width
imageftbbox -- Give the bounding box of a text using fonts via freetype2
imagefttext -- Write text to the image using fonts using FreeType 2
imagegammacorrect -- Apply a gamma correction to a GD image
imagegd2 -- Output GD2 image
imagegd -- Output GD image to browser or file
imagegif -- Output image to browser or file
imageinterlace -- Enable or disable interlace
imageistruecolor -- Finds whether an image is a truecolor image.
imagejpeg -- Output image to browser or file
imageline -- Draw a line
imageloadfont -- Load a new font
imagepalettecopy -- Copy the palette from one image to another
imagepng -- Output a PNG image to either the browser or a file
imagepolygon -- Draw a polygon
imagepsbbox --  Give the bounding box of a text rectangle using PostScript Type1 fonts
imagepscopyfont --  Make a copy of an already loaded font for further modification
imagepsencodefont -- Change the character encoding vector of a font
imagepsextendfont -- Extend or condense a font
imagepsfreefont -- Free memory used by a PostScript Type 1 font
imagepsloadfont -- Load a PostScript Type 1 font from file
imagepsslantfont -- Slant a font
imagepstext -- To draw a text string over an image using PostScript Type1 fonts
imagerectangle -- Draw a rectangle
imagerotate -- Rotate an image with a given angle
imagesavealpha --  Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images.
imagesetbrush -- Set the brush image for line drawing
imagesetpixel -- Set a single pixel
imagesetstyle -- Set the style for line drawing
imagesetthickness -- Set the thickness for line drawing
imagesettile -- Set the tile image for filling
imagestring -- Draw a string horizontally
imagestringup -- Draw a string vertically
imagesx -- Get image width
imagesy -- Get image height
imagetruecolortopalette -- Convert a true color image to a palette image
imagettfbbox -- Give the bounding box of a text using TrueType fonts
imagettftext -- Write text to the image using TrueType fonts
imagetypes -- Return the image types supported by this PHP build
imagewbmp -- Output image to browser or file
iptcembed -- Embed binary IPTC data into a JPEG image
iptcparse --  Parse a binary IPTC http://www.iptc.org/ block into single tags.
jpeg2wbmp -- Convert JPEG image file to WBMP image file
png2wbmp -- Convert PNG image file to WBMP image file
read_exif_data -- Alias of exif_read_data()


add a note add a note User Contributed Notes
Image functions
daniel @ swn
17-Sep-2003 09:55
For everyone trying to get jpeg support working:

Since I could not compile jpeg support with the bundled gd library in php 4.3.3, I tried with the external one and got some reference errors. If you get these errors when make'ing PHP, try to set the XPM directory when configuring gd2. I noticed that there are some error messages when compiling php with the default xpm setting in gd2's configure. Maybe there is something similar concerning freetype support, too...so I activated it however I need it or not.

What I did:

I downloaded and installed jpeg6b, freetype etc.:
./configure
make
make install

downloaded xpm and copied any files and directories to /usr/local

downloaded gd2 and installed it..
./configure --with-jpeg=/usr/local --with-freetype=/usr/local --with-png=/usr/local --with-xpm=/usr/local
[make clean]
make
make install

and when configuring gd2 told me that it could not compile xpm support. Maybe I did something wrong but now the php 'make' runs without errors:
./configure [...] --with-gd=/usr/local --with-jpeg-dir=/usr/local
make
make install

and the jpeg functions started to work...
da_linuxguru at NOSPAM dot hotmail dot com
11-Sep-2003 06:35
Installing Php with GD support

Packages Needed:
GD
zlib
libjpeg-6b
Php

Installing GD
a) ./configure
b) gmake, gmake install
Installing  Zlib
a) ./configure --shared
b) gmake, gmake install
Installing Libjpeg-6b
a) ./configure --enable-shared
b) gmake, gmake install

Assuming your apache installation is in the directory /www

Installing Php
./configure --with-apxs2=/www/bin/apxs --with-mysql --prefix=/www/php --with-config-file-path=/www/php --enable-track-vars --disable-cgi --with-gd=/usr/local --with-jpeg-dir=/usr/local

Finally, I had problems while compiling php ver 4.3.2 and 4.3.3 bot with the same problem related to a function in the file phpsourcedir/ext/gd/gd.c called Imagecache seomthing... I had to comment this line and then all went fine, however the tumbnails that I am still gettting are 256 colors only.

-Dhaval
pigmeu at pigmeu dot net
03-Sep-2003 02:09
I had some troubles when trying to resize an image gotten from a database blob field... Perhaps that these image functions don't work with opened image streams...

So, I had to make this workaround...

Use this code if you are trying to handle imagens from a database.

//...
    // creating a temp image name
    $t_img_name = tempnam ("/tmp", "timg");
    $t_img = fopen($t_img_name, "w");

    // $content is the blob field with the image.
    fwrite($t_img, $content);

    fclose($t_img);

    // now, do what want to with the image
    $size = getimagesize($t_img_name);
    echo $size[0]." - ".$size[1];

    // don't forget to delete the temp file after all.
    unlink($t_img_name);
//...
sameerni at netscape dot net
19-Aug-2003 02:30
i tried to install gd on linux (RedHat 8.0) with apache 1.3.27 and php 4.3.2
i had libjpeg, libz, libgif, libpng, libgd installed in /usr/lib.
i compiled php using following ./configure command:

./configure --prefix=/usr/local/php --with-apxs=/usr/local/apache/bin/apxs --with-mysql=/usr/local/mysql --with-gd --with-gd-dir=/usr/lib --with-freetype --with-freetype-dir=/usr/lib --enable-ftp --with-jpeg --with-jpeg-dir=/usr/lib --with-png --with-png-dir=/usr/lib --with-gif --with-gif-dir=/usr/lib --with-xml --with-xslt --with-zlib --with-zlib-dir=/usr/lib

it compiled without any problem. but phpinfo() did not show jpeg support.
and it did not find imagecreatefromjpeg() so i installed libjpeg-6b in different directory (in /usr/lib/jpeg6b) and recompiled php with following command.

./configure --prefix=/usr/local/php --with-apxs=/usr/local/apache/bin/apxs --with-mysql=/usr/local/mysql --with-gd --with-gd-dir=/usr/lib --with-freetype --with-freetype-dir=/usr/lib --enable-ftp --with-jpeg --with-jpeg-dir=/usr/lib/jpeg6b --with-png --with-png-dir=/usr/lib --with-gif --with-gif-dir=/usr/lib --with-xml --with-xslt --with-zlib --with-zlib-dir=/usr/lib

and imagecreatefromjpeg() started working.

also phpinfo() shows jpg support enabled.
----------output of phpinfo()-------------
[snip]
gd
GD Support enabled
GD Version bundled (2.0.12 compatible)
FreeType Support enabled
FreeType Linkage with freetype
GIF Read Support enabled
JPG Support enabled
PNG Support enabled
WBMP Support enabled
XBM Support enabled
[snip]
----------output of phpinfo()-------------

hope you will find this useful.
office at 4point-webdesign dot com
07-Jul-2003 04:29
Here's a funtion i used to resize and save images uploaded by the user, you can either create thumbnails or other images.
Main "feature" is that the width and height stay relativ to each other.

imgcomp is the quality, i turned it around so now its from 0 -best to 100 -most compressed.

For gif version just change the functions names.

function resampimagejpg($forcedwidth, $forcedheight, $sourcefile, $destfile, $imgcomp)
    {
    $g_imgcomp=100-$imgcomp;
    $g_srcfile=$sourcefile;
    $g_dstfile=$destfile;
    $g_fw=$forcedwidth;
    $g_fh=$forcedheight;

    if(file_exists($g_srcfile))
        {
        $g_is=getimagesize($g_srcfile);
        if(($g_is[0]-$g_fw)>=($g_is[1]-$g_fh))
            {
            $g_iw=$g_fw;
            $g_ih=($g_fw/$g_is[0])*$g_is[1];
            }
            else
            {
            $g_ih=$g_fh;
            $g_iw=($g_ih/$g_is[1])*$g_is[0];   
            }
        $img_src=imagecreatefromjpeg($g_srcfile);
        $img_dst=imagecreate($g_iw,$g_ih);
        imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);
        imagejpeg($img_dst, $g_dstfile, $g_imgcomp);
        imagedestroy($img_dst);
        return true;
        }
        else
        return false;
    }
dehumanizer at optusnet dot com dot au
31-May-2003 08:18
If you are trying to install jpeg support with php, then first install jpeg-6b and libpng. And when starting to install gd, check out the Makefile. I tried to install gd-1.8.4 and found that the Makefile didnt include the jpeglibs, rather all were commented. Uncomment the lines where you'll find the JPEG libs are mentioned. Like the lines below:
CFLAGS=-0 -DHAVE_LIBPNG -DHAVE_LIBJPEG
CFLAGS=-0 -DHAVE_LIBXPM -DHAVE_LIBPNG -DHAVE_LIBJPEG
There are several lines like that those you have to uncomment. Now install gd.
Before installing php, check if there is any config.cache file existing. If it does, delete it. The php ./configure sysntax should have --with-jpeg-dir --with-png-dir --with-gd=/path/to/gd
After configure is done, check out the config.cache file. If jpeg and png supports are installed successfully, you should be able to find these lines:
ac_cv_lib_gd_gdImageCreateFromJpeg=
${ac_cv_lib_gd_gdImageCreateFromJpeg=yes}
ac_cv_lib_gd_gdImageCreateFromPng=
${ac_cv_lib_gd_gdImageCreateFromPng=yes}
now, make and make install.
I put all the installers in one directory. So, this is how my dir-structure looked like
/opt/apache/download/upgrade/apache_1.3.27
/opt/apache/download/upgrade/gd-1.8.4
/opt/apache/download/upgrade/jpeg-6b
/opt/apache/download/upgrade/libpng-1.2.5
/opt/apache/download/upgrade/php-4.2.3

No directory prefix was used  while configuring gd/jpeg/libpng/

This worked for me pretty fine. Hope this will help and save time for someone.
sellout at NoSpAm dot dharmadevil dot com
17-Apr-2003 12: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 $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($img000);
 
$bg ImageColorAllocate($img255255255);
 
ImageFilledRectangle($img00$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');

?>
Angus Chung a swinburnemultimediastudent
03-Apr-2003 01:40
this code work faster in my p4 2G machine PHP Version 4.3.1 imageresampled() gives better quality however much slower when work on high resolution image , e.g. the DC photo.therefore i first use imageresized() to produce a middle size temp image, then imageresampled() the temp image to a smaller thumbnail and output to the browser

<?php 
$t_w 
444;   // temp image width x 3
$t_h 333// temp image height x 3

     
................
     
// get and create intermediate image
     
................
     
imagecopyresized ($destimage,$srcimage,0,0,0,0,$t_w,$t_h,$width,$height);

     
// process of the output thumbnail
     
$t_w2 round($t_w/3); //148
     
$t_h2 round($t_h/3); //111
     
$destimage2 imagecreatetruecolor($t_w2,$t_h2); // for output
     
imagecopyresampled ($destimage2,$destimage,0,0,0,0,$t_w2,$t_h2,$t_w,$t_h);
     
imagedestroy($destimage);
     
imageinterlace ($destimage2,1);//progressive jpeg
     
imagejpeg($destimage2''45); 
     
imagedestroy($destimage2); 
     .................
?>
RJ-Gerry at wiu dot edu
08-Mar-2003 04:00
I have successfully installed GD and FreeType 2 with PHP 4.3.0 on my OS X 10.2.4 (Jaguar) machine.  Using fink http://fink.sourceforge.net which comes with dselect (a menu ?based apt-get), I was able to download and install both GD and FreeType 2 without having to compile either one of them.  I was then able to add them into PHP by using this configure command (and then make and make install of course):

./configure --with-mysql --with-apxs --with-gd=/sw --with-freetype-dir=/sw --with-ttf

The directories for gd and freetype were both /sw because that is where fink installs its software.  I also added the ?with-ttf to make sure that True Type Fonts were supported.  Hope this helps any OS X users!
khyri at idyllmtn dot com
06-Mar-2003 03:00
To save others the hours I spent, I'd like to point out the
following:

Even if you are using the built-in GD libraries for 4.3.0 and
above, you still need to download and install jpeg-6b, libpng
and zlib before you can manipulate anything except read-only
gifs. These libraries are NOT bundled.

And they need to be installed as shared, not static libraries.
The default installation for jpeg-6b will only make a static
library (do ./configure --enabled-shared) and the selection
of makefile for libpng will determine whether you end up with
a shared or static library.
cysoft at php dot net
06-Mar-2003 12:32
How to using GD out put  chinese Characters (BIG 5 or GB2312).
the following code shows you how to using gd display chinese Characters.
there is a funcation called by ImageTTFText.
since gd dose not support GB2312/big5 but unicode.if you can convert
Characters to unicode which you want display then every thing will be done!
your 's yan
<?php
function gb23122uni($text) {
       
$rtext="";
       
$max=strlen($text);
        for(
$i=0;$i<$max;$i++){
         
$h=ord($text[$i]);
          if(
$h>=160 && $i<$max-1){
           
$rtext.="&#".base_convert(bin2hex(iconv("gb2312","ucs-2",
             
substr($text,$i,2))),16,10).";";
           
$i++;
          }else{
           
$rtext.=$text[$i];
          }
        }
        return 
$rtext;
 }
Header("Content-type: image/gif");
$im imagecreate(400,50);
$black ImageColorAllocate($im0,255,0);
$white ImageColorAllocate($im255,0,255);

ImageTTFText($im2003030$white"c:\php\STCAIYUN.ttf",gb23122uni("
斕疑"
)."test");
Imagejpeg($im);
ImageDestroy($im);
?>
bermi.ferrer ) a.t ( akelos d搗暗 com
27-Feb-2003 06:02
From PHP 4.3.X if the image color changes or its loosy use ImageCreateTrueColor() instead of ImageCreate()
sir_hmba at NOSPAMyahoo dot com
17-Jan-2003 02:13
The GD library, prior to 2.x, does not appear to process images with more than 256 colors without first converting them to a 256 color indexed (palette) image.

In other words, if you have a truecolor JPEG or PNG and you load the image up with these functions (e.g., imagecreatefrompng()) then the internal resource will be a palettized version of your original.  The only information I found about this were in a few separate comments spread around this section.

If you compile PHP with a 2.0 or higher version of the GD library, then the internal image resource will not be subjected to this automatic conversion.  I believe that all the RedHat PHP RPMs (as of today) still come compiled with the older version of GD (pre 2.0).
dbonomo at 3drealm dot net
27-Dec-2002 09:01
This may be a known thing among the more experienced programmers here, but a basic piece of information needed to allow you to include a php-generated image in a page with other content is that you treat it as if it were an image.  Here is an example of what I mean:
<img src=filename.php?var1=val1&var2=val2>

In the above example filename.php is the php file that has all the image generation code.

The php you write to create the picture is essentially a picture itself, and needs to be treated as such.  Maybe Im being thick, but it took a couple of days of hammering away at it to be able to mix php-generated images with the rest of the page's content.

I am so far very impressed with how straightforward this all is.  I have been avoiding this aspect of the code but now I love it.

Hope this helps.

Doug Bonomo
webmaster at wutallan dot net
14-Dec-2002 03:47
Installing PHP with GD2 support on a system running Debian Woody is quite easy. You just need to install the deb packages of the libs, including the -dev packages. Do this with one apt-get command:

apt-get install libgd2 libgd2-dev libjpeg62 libjpeg62-dev libpng2 libpng2-dev libfreetype6 libfreetype6-dev

(libpng depends on zlib, so it will automatically be installed)
Having those libs installed, add this to your PHP configure command:

--with-gd --with-jpeg-dir=/usr/lib --with-png-dir=/usr/lib --with-freetype-dir=/usr/lib --with-zlib-dir=/usr/lib
oerisen at netscape dot net
13-Dec-2002 07:18
if you have PHP 4.2.3 windows binaries then just uncomment the line
;extension=php_gd.dll
then restart your web server

GD, and Freetype is enabled

but be careful when u use
imagettftext
you must point the correct path to the TTf font file !!!
but you must be twice careful some windows TTF (times, tahoma,...)fonts are not rendered and gives an error like

"The image ... cannot be displayed, because it contains errors"

I tested arial and verdena works fine :)

imagettftext ($im, $size, $angle, $left,$bottomleft , $col, $font, $text);

for windows it's best practice to place font files ander php folder and use them from that location
imagettftext ($im, $size, $angle, $left,$bottomleft , $col, "c:\php\fonts\arial.ttf", $text);

Ihope this will save some time for beginners

(at first, i enabled gd and tried times.ttf :-( this cost me a week to solve this problem i searched every website and find nearly nothing
polak underscore sg at hotmail dot com
22-Nov-2002 08:54
be careful about your version of php and gd lib!
the newer versions of php needs gd2
and don't forget to specify the header before creating the image
karpet at comatosed dot co dot uk
10-Nov-2002 08:32
It would seem in version 2.0.4 of gd, there's been a change in the definition of struct gdIOCtx (defined in gd_io.h), which for me caused the following error:
gd_ctx.c:70: structure has no member named `free'
and similiar, relating errors from gd.c and gd_ctx.c, preventing me compiling php with gd support.
The solution that appears to work without problems is to simply edit gd.c and gd_ctx.c (in ext/gd, in php's codetree), and replace all occurances of "->free" with "->gd_free".
myk at dnagroup dot com dot au
26-Jul-2002 03:35
On RedHat 7.1 if you get a configure error when looking for XpmFreeXpmImage in libXpm it might pay to make sure both XFree86-libs*.rpm and XFree86-devel*.rpm are installed.

I only had libs installed and was pulling my hair out.
aleczapka at gmx dot net
12-Jun-2002 09:21
Even if you don't intend to use PNGs, but only JPEG files with GD & PHP - you need to pass the --with-png parameter (in case PHP won't find it) to configure.
Otherwise you will get GD support = YES but functions like gdImageCreateFromJpeg won't work without png library.
jmcastagnetto at php dot net
26-Mar-2002 11:12
For those looking for more information on how to get GD 2 working with PHP, see the steps suggested by Rasmus at:

http://www.php.net/~rasmus/gd.html
fred1224 at sinaman dot com
10-Mar-2002 12:06
If your site is hosting in ISP, not your own server.
If your ISP doesn't support ImageMagick, you need to install it by yourself.
Then, you may need to put this scripts.

$im = "path.of.your.im.dir";
$convert = $im."/convert";
putenv("LD_LIBRARY_PATH=$im");
putenv("MAGICK_HOME=$im");

Setting the enviroment for the im.
stefan dot wehowsky at profilschmiede dot de
02-Feb-2002 07:57
If you ever want to resize a picture (maybe in order to create a thumbnail), this small function
should help you. It also gives you an idea of how some of the basic image functions of PHP can be
used.

/* resizeToFile resizes a picture and writes it to the harddisk
 * 
 * $sourcefile = the filename of the picture that is going to be resized
 * $dest_x       = X-Size of the target picture in pixels
 * $dest_y       = Y-Size of the target picture in pixels
 * $targetfile = The name under which the resized picture will be stored
 * $jpegqual   = The Compression-Rate that is to be used
 */

function resizeToFile ($sourcefile, $dest_x, $dest_y, $targetfile, $jpegqual)
{
   

/* Get the dimensions of the source picture */
    $picsize=getimagesize("$sourcefile");

    $source_x  = $picsize[0];
    $source_y  = $picsize[1];
    $source_id = imageCreateFromJPEG("$sourcefile");

/* Create a new image object (not neccessarily true colour) */
       
    $target_id=imagecreatetruecolor($dest_x, $dest_y);

/* Resize the original picture and copy it into the just created image
   object. Because of the lack of space I had to wrap the parameters to
   several lines. I recommend putting them in one line in order keep your
   code clean and readable */
       

    $target_pic=imagecopyresampled($target_id,$source_id,
                                   0,0,0,0,
                                   $dest_x,$dest_y,
                                   $source_x,$source_y);

/* Create a jpeg with the quality of "$jpegqual" out of the
   image object "$target_pic".
   This will be saved as $targetfile */
 
    imagejpeg ($target_id,"$targetfile",$jpegqual);

    return true;

}
mrcheezy at hotmail dot com
10-Jan-2002 01:55
Want to be able to open gifs?

In the www.php4win.de build of php there is a dll called php_gd_gif.dll. Rename this to php_gd.dll and move it into your extensions directory.

*Make sure you back up the old dll!*
cv at corbach dot de
15-Dec-2001 08:26
To use freetype2 with TTF functions you need to specify

--with-freetype-dir

AND

--with-ttf

for your build (the output of configure seems as if you don't have to specify --with-ttf but you need to).
mrobinso at php dot net
06-Dec-2001 12:01
There's a bug in GD2 < 2.0.2 that prevents antialiasing from working properly. The fix for this should be in gd-2.0.2 if the GD people get around to it. This isn't a bug in php.
mkinsman at tcs-basys dot com
06-Nov-2001 07:10
Thanks for the notes on testing gd support in the distribution! It did save me a lot of time! Just an update, though. Your code didn't work right off the bat for my system, because later versions of PHP may not support GIF format due to 'copyright stuff'. However, it's easy enough to change the code to output as JPEG or PNG or whatever. For example, to test JPEG support instead:

                      // create the image
                      $gif = ImageCreate(200,200);
                      $bg = ImageColorAllocate($gif,0,0,0);
                      $tx = ImageColorAllocate($gif,255,128,128);
                      ImageFilledRectangle($gif,0,0,200,200,$bg);
                      ImageString($gif,3,70,90,"it works !",$tx);

                      // send the image
                      header("content-type: image/jpeg");
                      ImageJPEG($gif);

                      That's all folks !!
ihayes at earthling dot net
19-Oct-2001 10:14
<p>With GD 2 and PHP 4.06 on win 2000, the TTF fonts need to be on the drive where the script is called from, not where PHP is installed.</p><p>I have PHP installed on drive C:. The scripts are on drive Q:. The fonts must be in stalled on Q:. </P><P>eg. The fonts are installed in "Q:\fonts" and must be referenced by "/fonts/<fontname>.ttf"
npdavis at hotmail dot com
25-May-2001 12:45
I build menus using image functions. I noticed that even if you preload the images, some do not always load. In addition the image generation puts a load on the server... the answer? Cache Control headers. These headers will cause IE and Netscape to load all images correctly and also force the proxys and web caches to cache them, allowing your pages to render correctly, AND save you lots of cycles: ) These headers tell both the browser and the ISP caches/proxys to cache the images.

Here is the code:

Header ("Last-Modified: " . gmdate("D, d M Y H:i:s",mktime (0,0,0,1,1,2000)) . " GMT");  // Date in the past
Header ("Expires: Mon, 26 Jul 2040 05:00:00 GMT");    // In other words... never expire the image
Header ("Cache-Control: max-age=10000000, s-maxage=1000000, proxy-revalidate, must-revalidate");//Cache-Control header is ESSENTIAL for forcing Netscape to load all images!... and telling the ISP caches to do the same in this case cache for 1 million seconds.

These headers may or may not be redundant... any input is welcome.

In addition, it is essential for proxys and ISP caches that your re-used images have the same url... IE create a generic image creation script, and feed it parameters. This way your
http://yoursite/imagegen.php?text=home&h=40&w=150&fontsize=13 Home link image has the same url on all of your pages... This will make your images more proxy/cacheserver cache AND browser cache friendly.

thx,
Neil
icecube at fr dot fm
20-May-2001 03:31
Improved version of ResizeGif given by tjhunter with Height % Widht.

<?php 
/* ResizeGif with (height % width) */
function RatioResizeImg$image$newWidth$newHeight){ 

//Open the gif file to resize
eregi(".(.*)$",$image,$regs);
switch(
$regs[1]){ 
 case 
"gif"$srcImage ImageCreateFromGIF$image ); break; 
 case 
"jpg"$srcImage ImageCreateFromJPEG$image ); break; 
 case 
"png"$srcImage ImageCreateFromPNG$image ); break; 
 default: 
$srcImage ImageCreateFromGIF$image ); break;} 

 

//obtain the original image Height and Width
$srcWidth ImageSX$srcImage ); 
$srcHeight ImageSY$srcImage ); 


// the follwing portion of code checks to see if
// the width > height or if width < height
// if so it adjust accordingly to make sure the image
// stays smaller then the $newWidth and $newHeight

$ratioWidth $srcWidth/$newWidth;
$ratioHeight $srcHeight/$newHeight;

if( 
$ratioWidth $ratioHeight){ 

$destWidth $srcWidth/$ratioHeight;
$destHeight $newHeight
}else{ 

$destWidth $newWidth
$destHeight $srcHeight/$ratioWidth



// creating the destination image with the new Width and Height
$destImage imagecreate$destWidth$destHeight); 

//copy the srcImage to the destImage
ImageCopyResized$destImage$srcImage0000$destWidth$destHeight$srcWidth$srcHeight ); 

//create the gif
ImageGif$destImage ); 


//fre the memory used for the images
ImageDestroy$srcImage ); 
ImageDestroy$destImage ); 



//save output to a buffer
ob_start(); 

//Resize image ( will be stored in the buffer )
ResizeGif"/where/image/is/image.gif""150""150"); 

//copy output buffer to string
$resizedImage ob_get_contents(); 

//clear output buffer that was saved
ob_end_clean(); 


//write $resizedImage to Database, file , echo to browser whatever you need to do with it
?>
leefelix at pacific dot net dot hk
12-Mar-2001 02:12
For those of you who wants to compile PHP as Apache static module but failed in compiling Apache (undefined some PNG_XXX) functions, try re-ordering the -l parameters in Apache Makefiles (there are several) so that "-lgd is loaded before -lpng".
07-Mar-2001 03:29
When using ImageGif( $im ) it sends the output directly to the browser. to prevent this from happening and also to be able to save your new image to a database for example use ob_start(), ob_get_contents(), and ob_end_clean() <BR><BR>ex:<BR> <?php <BR>function ResizeGif$image$newWidth$newHeight){

   
//Open the gif file to resize
   
$srcImage ImageCreateFromGif$image );

   
//obtain the original image Height and Width
   
$srcWidth  ImageSX$srcImage );
   
$srcHeight ImageSY$srcImage );

   
   
// the follwing portion of code checks to see if
    // the width > height or if width < height
    // if so it adjust accordingly to make sure the image
    // stays smaller then the $newWidth and $newHeight

   
if( $srcWidth $srcHeight ){

       
$destWidth  $newWidth $srcWidth/$srcHeight;
       
$destHeight $newHeight;
    }else{

       
$destWidth  $newWidth;
       
$destHeight $newHeight $srcHeight/$srcWidth;
    }

   
   
// creating the destination image with the new Width and Height
   
$destImage imagecreate$destWidth$destHeight); 

   
//copy the srcImage to the destImage
   
ImageCopyResized$destImage$srcImage0000$destWidth$destHeight$srcWidth$srcHeight );

   
//create the gif
   
ImageGif$destImage );
   

   
//fre the memory used for the images
   
ImageDestroy$srcImage  );
   
ImageDestroy$destImage );
   
}

       
//save output to a buffer
       
ob_start();
   
       
//Resize image  ( will be stored in the buffer )
       
ResizeGif"/where/image/is/image.gif""150""150");
       
       
//copy output buffer to string
       
$resizedImage ob_get_contents();
       
       
//clear output buffer that was saved
       
ob_end_clean();
       
       
       
bene[nospam] at iolvegas dot com
30-Jan-2001 02:23
If you get these errors while trying to compile:

gd.c: In function `php_if_imagecreatefromgif':
gd.c:709: `gdImageCreateFromGif' undeclared (first use in this function)
gd.c:709: (Each undeclared identifier is reported only once
gd.c:709: for each function it appears in.)
gd.c:709: `gdImageCreateFromGifCtx' undeclared (first use in this function)
gd.c: In function `php_if_imagegif':
gd.c:891: `gdImageGif' undeclared (first use in this function)

Then you are using an old version of gd.h and probably didn't specify the PATH on --with-gd  ... Slackware on my systems had an old gd.h hidden away ...

Be warned!

./configure --with-gd=/usr/local
anders at gerf dot dk
18-Oct-2000 08:48
I've found that one of the things that most often fails when installing PHP with GD support is that the path to GD is specified wrong or not specified at all. The placement PHP considers to be GD's default install dir is not what GD considers it to be, GD will most likely be installed in /usr/local unless otherwise specified. So the parameter to pass to configure is --with-gd=/usr/local or whereever you have put GD.
rick at e-possibility dot com
28-Jul-2000 09:36
FINALLY -- here is what I had to do to compile PHP with image creation on FreeBSD4.0; I hope this is at least somewhat helpful to Linux users also:

(Notes: I used gmake instead of make, but if you don't have gmake, it should still work with 'make' and 'make install'. I used the DSO install method with Apache; I have not yet done this as a static linked install)

1. Assume X-windows, libpng, mysql, gmake and automake are already installed.

2. Install libjpeg (from
ftp://ftp.uu.net/graphics/jpeg/jpegsrc.v6b.tar.gz )
        a) ./configure --enable-shared
        b) gmake, gmake install

3. Install Freetype 1.3.1 (from http://www.freetype.org)
        a) ./configure --enable-shared --x-includes=/usr/X11R6/include --x-libraries=/usr/X11R6/lib
        b) gmake, gmake install
        c) if freetype creates a freetype/ directory inside /usr/local/lib, copy all contents into /usr/local/lib

4. Install zlib 1.1.3 (from http://www.info-zip.org/pub/infozip/zlib/)
        a) ./configure --shared
        b) gmake, gmake install

5. Install gd-1.8.3 (from http://www.boutell.com/gd)
        a) edit Makefile for correct include and lib dirs, and uncomment the lines that enable all options, while commenting out the default lines
        b) edit gd.c; remove 1st three lines (if - endif for malloc.h)
        c) edit gdcache.h and ...php-src/ext/gd/gdcache.h (if exists) and replace <malloc.h> with <stdlib.h>
        d) copy /usr/X11R6/include/X11 to /usr/X11R6/include/X11/X11 (gd looks recursively inside X11 to X11/*)
        e) gmake, gmake install

6. Install apache-1.3.12
        a) ./configure --prefix=/usr/local/apache --enable-module=all --enable-shared=max
        b) gmake, gmake install

7. Install PHP 4.0.1pl2
        a) ./configure --prefix=/usr/local/php4 --with-mysql --with-apxs=/usr/local/apache/bin/apxs --enable-track-vars --with-gd=/usr/local/ --with-jpeg-dir=/usr/local --with-xpm-dir=/usr/X11R6 --with-zlib-dir=shared
        b) gmake, gmake install
        c) sometimes I have found you need to reboot the system completely instead of just restart httpd

have fun ;-)
eric at spotgrafix dot com
26-Jul-2000 03:24
After a day's worth of hassle, I discovered that the solution to making gifs (no LZW so it's legal) is to use ImageMagick. You can get it at
ftp://ftp.wizards.dupont.com/pub/ImageMagick/ImageMagick-5.2.2.tar.gz

The following code works:

<?php
$fonts
=Array('coolvet.ttf','doodle.ttf','gas.ttf',
'guinea.ttf','hijinx.ttf','hypno.ttf');
$fontname='/home/eric/public_html/imagephp/'.$fonts[$font];
list(
$llx,$lly,$lrx,$lry,$urx,$ury,$ulx,$uly)=imageTTFbbox($size,0,$fontname,$text);
$id=imagecreate(abs($urx-$ulx)+10,abs($lly-$ury)+8);
$blackImageColorAllocate($id000);
$whiteImageColorAllocate($id250250250);
imagefill($id,0,0,$white);
imagettftext($id,$size,0,0,abs($ury-$lry)+2,$black,$fontname,$text);
Header("Content-type: image/gif");
ImagePNG($id,"/tmp/test.png");
passthru("/usr/local/bin/convert /tmp/test.png gif:-");
imagedestroy($id)
?>

Now if there was only a way to get ImagePNG to output to a pipe, we could use:

ImagePNG($id,'|/usr/local/bin/convert png:- gif:-')
johntarter at hotmail dot com
09-Sep-1999 02:06
It is easy to use ImageMagick to generate images dynamically in php3.  Here is an example:

<?php
Header
("Content-type: image/gif"); passthru("/opt/x11/bin/convert -crop 0x0 -bordercolor white -border 10x10 inputfile.gif GIF:-
?>

The header is important, the passthru functions means binary data will be safe, and "
-" means ImageMagick will print to stdout instead of saving to a file.

<ob_iconv_handlerexif_imagetype>
 Last updated: Thu, 21 Aug 2003
show source | credits | sitemap | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: http://php.mirrors.ilisys.com.au/
Last updated: Sat 01 Nov 2003 04:13:36 EST EST