Image functionsGraphics
You can use the image functions in PHP to get the size of JPEG, GIF, and
PNG images, and if you have the GD library (available at &url.gd;) you will also be able to create and
manipulate images.
GetImageSizeget the size of a GIF, JPG or PNG imageDescriptionarray getimagesizestring filenamearray imageinfo
The GetImageSize function will determine the
size of any GIF, JPG or
PNG image file and return the dimensions along
with the file type and a height/width text string to be used
inside a normal HTML IMG
tag.
Returns an array with 4 elements. Index 0 contains the width of
the image in pixels. Index 1 contains the height. Index 2 a flag
indicating the type of the image. 1 = GIF, 2 = JPG, 3 = PNG.
Index 3 is a text string with the correct "height=xxx width=xxx"
string that can be used directly in an IMG tag.
GetImageSize
<?php $size = GetImageSize("img/flag.jpg"); ?>
<IMG SRC="img/flag.jpg" <?php echo $size[3]; ?>>
The optional imageinfo parameter allows you to
extract some extended information from the image file. Currently this
will return the diffrent JPG APP markers in an
associative Array. Some Programs use these APP markers to embedd text
information in images. A very common one in to embed IPTC &url.iptc; information in the APP13 marker. You
can use the iptcparse function to parse the binary
APP13 marker into something readable.
GetImageSize returning IPTC
<?php
$size = GetImageSize("testimg.jpg",&$info);
if (isset($info["APP13"])) {
$iptc = iptcparse($info["APP13"]);
var_dump($iptc);
}
?>
This function does not require the GD image library.
ImageArcdraw a partial ellipseDescriptionint imagearcint imint cxint cyint wint hint sint eint col
ImageArc draws a partial ellipse centered at cx, cy (top left is
0,0) in the image represented by im. w and h specifies the
ellipse's width and height respectively while the start and end
points are specified in degrees indicated by the s and e
arguments.
ImageChardraw a character horizontallyDescriptionint imagecharint imint fontint xint ystring cint col
ImageChar draws the first character of c in the image
identified by id with its upper-left at
x,y (top left is 0,0) with the
color col. If font is 1, 2, 3, 4 or 5, a built-in font is
used (with higher numbers corresponding to larger fonts).
See also imageloadfont.
ImageCharUpdraw a character verticallyDescriptionint imagecharupint imint fontint xint ystring cint col ImageCharUp draws the character c vertically in the
image identified by im at coordinates x,
y (top left is 0, 0) with the color col.
If font is 1, 2, 3, 4 or 5, a built-in font is used.
See also imageloadfont.
ImageColorAllocateallocate a color for an imageDescriptionint imagecolorallocateint imint redint greenint blue
ImageColorAllocate returns a color identifier representing the color composed of
the given RGB components. The im argument is the return from the
imagecreate function. ImageColorAllocate must be called to
create each color that is to be used in the image represented by im.
$white = ImageColorAllocate($im, 255,255,255);
$black = ImageColorAllocate($im, 0,0,0);
ImageColorAtget the index of the color of a pixelDescriptionint imagecoloratint imint xint y
Returns the index of the color of the pixel at the
specified location in the image.
See also imagecolorset and
imagecolorsforindex.
ImageColorClosestget the index of the closest color to the specified colorDescriptionint imagecolorclosestint imint redint greenint blue
Returns the index of the color in the palette of the image
which is "closest" to the specified RGB value.
The "distance" between the desired color and each color in the palette is
calculated as if the RGB values represented points in three-dimensional
space.
See also imagecolorexact.
ImageColorExactget the index of the specified colorDescriptionint imagecolorexactint imint redint greenint blue
Returns the index of the specified color in the palette of the image.
If the color does not exist in the image's palette, -1 is returned.
See also imagecolorclosest.
ImageColorResolveget the index of the specified color or its closest possible alternativeDescriptionint imagecolorresolveint imint redint greenint blue
This function is guaranteed to return a color index for a requested color, either the exact color
or the closest possible alternative.
See also imagecolorclosest.
ImageColorSetset the color for the specified palette indexDescriptionbool imagecolorsetint imint indexint redint greenint blue
This sets the specified index in the palette to the specified
color. This is useful for creating flood-fill-like effects in
paletted images without the overhead of performing the actual
flood-fill.
See also imagecolorat.
ImageColorsForIndexget the colors for an indexDescriptionarray imagecolorsforindexint imint index
This returns an associative array with red, green, and blue keys
that contain the appropriate values for the specified color index.
See also imagecolorat and
imagecolorexact.
ImageColorsTotalfind out the number of colors in an image's paletteDescriptionint imagecolorstotalint im
This returns the number of colors in the specified image's palette.
See also imagecolorat and
imagecolorsforindex.
ImageColorTransparentdefine a color as transparentDescriptionint imagecolortransparentint imint col
ImageColorTransparent sets the transparent color in the im image
to col. im is the image identifier returned by imagecreate
and col is a color identifier returned by
imagecolorallocate.
The identifier of the new (or current, if none is specified) transparent
color is returned.
ImageCopyResizedcopy and resize part of an imageDescriptionint imagecopyresizedint dst_imint src_imint dstXint dstYint srcXint srcYint dstWint dstHint srcWint srcH
ImageCopyResized copies a rectangular portion of one image to
another image. dst_im is the destination
image, src_im is the source image
identifier. If the source and destination coordinates and width
and heights differ, appropriate stretching or shrinking of the
image fragment will be performed. The coordinates refer to the
upper left corner. This function can be used to copy regions
within the same image (if dst_im is the
same as src_im) but if the regions overlap
the results will be unpredictable.
ImageCreatecreate a new imageDescriptionint imagecreateint x_sizeint y_size ImageCreate returns an image identifier representing a blank image
of size x_size by y_size.
ImageCreateFromGifcreate a new image from file or URLDescriptionint imagecreatefromgifstring filenameimagecreatefromgif returns an image identifier
representing the image obtained from the given filename.
imagecreatefromgif returns an empty string
on failure. It also outputs an error message, which unfortunately
displays as a broken link in a browser. To ease debugging the
following example will produce an error GIF:
Example to handle an error during creation (courtesy vic@zymsys.com )
function LoadGif($imgname)
{
$im = @imagecreatefromgif($imgname); /* Attempt to open */
if ($im == "") { /* See if it failed */
$im = ImageCreate(150,30); /* Create a blank image */
$bgc = ImageColorAllocate($im,255,255,255);
$tc = ImageColorAllocate($im,0,0,0);
ImageFilledRectangle($im,0,0,150,30,$bgc);
ImageString($im,1,5,5,"Error loading $imgname",$tc); /* Output an errmsg */
}
return $im;
}
Since all GIF support was removed from the GD library in version 1.6,
this function is not available if you are using that version of the
GD library.
ImageDashedLinedraw a dashed lineDescriptionint imagedashedlineint imint x1int y1int x2int y2int col ImageLine draws a dashed line from x1,y1 to
x2,y2 (top left is
0,0) in image im of color
col.
See also imageline.
ImageDestroydestroy an imageDescriptionint imagedestroyint im ImageDestroy frees any memory associated with image im. im is the
image identifier returned by the imagecreate
function.
ImageFillflood fillDescriptionint imagefillint imint xint yint col ImageFill performs a flood fill starting at coordinate x, y (top left is 0,0) with color col in the image im.
ImageFilledPolygondraw a filled polygonDescriptionint imagefilledpolygonint imarray pointsint num_pointsint col ImageFilledPolygon creates a filled polygon in image im. points is a PHP array containing the
polygon's vertices, ie. points[0] = x0,
points[1] = y0, points[2] = x1,
points[3] = y1, etc. num_points is the
total number of vertices.
ImageFilledRectangledraw a filled rectangleDescriptionint imagefilledrectangleint imint x1int y1int x2int y2int col ImageFilledRectangle creates a filled rectangle of color col in
image im starting at upper left coordinates x1,
y1 and ending at bottom right coordinates x2, y2. 0, 0 is the
top left corner of the image.
ImageFillToBorderflood fill to specific colorDescriptionint imagefilltoborderint imint xint yint borderint col ImageFillToBorder performs a flood fill whose border color is
defined by border. The starting point for the fill
is x,y (top left is
0,0) and the region is filled with color
col.
ImageFontHeightget font heightDescriptionint imagefontheightint font
Returns the pixel height of a character in the specified font.
See also imagefontwidth and
imageloadfont.
ImageFontWidthget font widthDescriptionint imagefontwidthint font Returns the pixel width of a character in font.
See also imagefontheight and imageloadfont.
ImageGifoutput image to browser or fileDescriptionint imagegifint imstring filenameimagegif creates the GIF file in filename from
the image im. The im
argument is the return from the imagecreate
function.
The image format will be GIF87a unless the image has been made
transparent with imagecolortransparent, in
which case the image format will be GIF89a.
The filename argument is optional, and if left off, the raw image
stream will be output directly. By sending an image/gif content-type
using header, you can create a PHP script that
outputs GIF images directly.
Since all GIF support was removed from the GD library in version 1.6,
this function is not available if you are using that version of the
GD library.
ImageInterlaceenable or disable interlaceDescriptionint imageinterlaceint imint interlaceImageInterlace turns the interlace bit on or off.
If interlace is 1 the im image will be interlaced, and if interlace
is 0 the interlace bit is turned off.
This functions returns whether the interlace bit is set for the image.
ImageLinedraw a lineDescriptionint imagelineint imint x1int y1int x2int y2int col ImageLine draws a line from x1,y1 to
x2,y2 (top left is
0,0) in image im of color
col.
See also imagecreate and imagecolorallocate.
ImageLoadFontload a new fontDescriptionint imageloadfontstring file
ImageLoadFont loads a user-defined bitmap font and returns an
identifier for the font (that is always greater than 5, so it will
not conflict with the built-in fonts).
The font file format is currently binary and architecture
dependent. This means you should generate the font files on the
same type of CPU as the machine you are running PHP on.
Font file formatbyte positionC data typedescriptionbyte 0-3intnumber of characters in the fontbyte 4-7int
value of first character in the font (often 32 for space)
byte 8-11intpixel width of each characterbyte 12-15intpixel height of each characterbyte 16-char
array with character data, one byte per pixel in each
character, for a total of (nchars*width*height) bytes.
See also ImageFontWidth and
ImageFontHeight.
ImagePolygondraw a polygonDescriptionint imagepolygonint imarray pointsint num_pointsint col ImagePolygon creates a polygon in image id. points is a PHP array containing the polygon's vertices,
ie. points[0] = x0, points[1] = y0,
points[2] = x1, points[3] = y1, etc. num_points is the total number of vertices.
See also imagecreate.
ImagePSBBoxgive the bounding box of a text rectangle using PostScript Type1 fontsDescriptionarray imagepsbboxstring textint fontint sizeint spaceint widthfloat anglesize is expressed in pixels.
space allows you to change the default value of a space in a font.
This amount is added to the normal value and can also be negative.
tightness allows you to control the amount of white space
between characters. This amount is added to the normal character width and can also be negative.
angle is in degrees.
Parameters space and tightness
are expressed in character space units, where 1 unit is 1/1000th of an em-square.
Parameters space, tightness and
angle are optional.
The bounding box is calculated using information available from character metrics,
and unfortunately tends to differ slightly from the results achieved by actually
rasterizing the text. If the angle is 0 degrees, you can expect the text to need
1 pixel more to every direction.
This function returns an array containing the following elements:
0lower left x-coordinate1lower left y-coordinate2upper right x-coordinate3upper right y-coordinate
See also imagepstext.
ImagePSEncodeFontchange the character encoding vector of a fontDescriptionint imagepsencodefontstring encodingfile
Loads a character encoding vector from from a file and changes the fonts
encoding vector to it. As a PostScript fonts default vector lacks most of the
character positions above 127, you'll definitely want to change this if
you use an other language than english. The exact format of this file is
described in T1libs documentation. T1lib comes with two ready-to-use files,
IsoLatin1.enc and IsoLatin2.enc.
If you find yourself using this function all the time, a much
better way to define the encoding is to set ps.default_encoding in
the configuration file
to point to the right encoding file and all fonts you load will
automatically have the right encoding.
ImagePSFreeFontfree memory used by a PostScript Type 1 fontDescriptionvoid imagepsfreefontint fontindex
See also imagepsloadfont.
ImagePSLoadFontload a PostScript Type 1 from fileDescriptionint imagepsloadfontstring filename
In the case everything went right, a valid font index will be returned and
can be used for further purposes. Otherwise the function returns false and
prints a message describing what went wrong.
See also imagepsfreefont.
ImagePSTextto draw a text string over an image using PostScript Type1 fontsDescriptiomarray imagepstextint imagestring textint fontint sizeint foregroundint backgroundint xint yint spaceint tightnessfloat angleint antialias_stepssize is expressed in pixels.
foreground is the color in which the text
will be painted. background is the color
to which the text will try to fade in with antialiasing. No
pixels with the color background are
actually painted, so the background image does not need to be of
solid color.
The coordinates given by x,
y will define the origin (or reference
point) of the first character (roughly the lower-left corner of
the character). This is different from the
ImageString, where x, y define the
upper-right corner of the first character. Refer to PostScipt
documentation about fonts and their measuring system if you have
trouble understanding how this works.
space allows you to change the default
value of a space in a font. This amount is added to the normal
value and can also be negative.
tightness allows you to control the amount
of white space between characters. This amount is added to the
normal character width and can also be negative.
angle is in degrees.
antialias_steps allows you to control the
number of colours used for antialiasing text. Allowed values are
4 and 16. The higher value is recommended for text sizes lower
than 20, where the effect in text quality is quite visible. With
bigger sizes, use 4. It's less computationally intensive.
Parameters space and
tightness are expressed in character space
units, where 1 unit is 1/1000th of an em-square.
Parameters space,
tightness, angle
and antialias are optional.
This function returns an array containing the following elements:
0lower left x-coordinate1lower left y-coordinate2upper right x-coordinate3upper right y-coordinate
See also imagepsbbox.
ImageRectangledraw a rectangleDescriptionint imagerectangleint imint x1int y1int x2int y2int col ImageRectangle creates a rectangle of color col in image im
starting at upper left coordinate x1,y1 and ending at bottom right coordinate x2,y2. 0,0 is the top
left corner of the image.
ImageSetPixelset a single pixelDescriptionint imagesetpixelint imint xint yint col ImageSetPixel draws a pixel at x,y
(top left is 0,0) in image im
of color col.
See also imagecreate and imagecolorallocate.
ImageStringdraw a string horizontallyDescriptionint imagestringint imint fontint xint ystring sint col ImageString draws the string s in the image identified by im at coordinates x,y (top
left is 0,0) in color col. If
font is 1, 2, 3, 4 or 5, a built-in font is used.
See also imageloadfont.
ImageStringUpdraw a string verticallyDescriptionint imagestringupint imint fontint xint ystring sint col ImageStringUp draws the string s vertically in the image
identified by im at coordinates x,y (top left is 0,0)
in color col.
If font is 1, 2, 3, 4 or 5, a built-in font is used.
See also imageloadfont.
ImageSXget image widthDescriptionint imagesxint im ImageSX returns the width of the image identified by
im.
See also imagecreate and imagesy.
ImageSYget image heightDescriptionint imagesyint im
ImageSY returns the height of the image identified by im.
See also imagecreate and
imagesx.
ImageTTFBBoxgive the bounding box of a text using TypeType fontsDescriptionarray ImageTTFBBoxint sizeint anglestring fontfilestring text
This function calculates and returns the bounding box in pixels
a TrueType text.
textThe string to be measured.
sizeThe font size.
fontfileThe name of the TrueType font file. (Can
also be an URL.)
angleAngle in degrees in which
text will be measured.
ImageTTFBBox returns an array with 8
elements representing four points making the bounding box of the
text:
0lower left corner, X position1lower left corner, Y position2lower right corner, X position3lower right corner, Y position4upper right corner, X position5upper right corner, Y position6upper left corner, X position7upper left corner, Y position
The points are relative to the text
regardless of the angle, so "upper left" means in the top
left-hand corner seeing the text horizontallty.
This function requires both the GD library and the Freetype library.
See also ImageTTFText.
ImageTTFTextwrite text to the image using a TrueType fontsDescriptionarray ImageTTFTextint imint sizeint angleint xint yint colstring fontfilestring text
ImageTTFText draws the string text in the
image identified by im, starting at
coordinates x,y (top left is 0,0), at an
angle of angle in color
col, using the TrueType font file
identified by fontfile.
The coordinates given by
x,y will define the
basepoint of the first character (roughly the lower-left corner
of the character). This is different from the
ImageString, where x,y define the
upper-right corner of the first character.
angle is in degrees, with 0 degrees being
left-to-right reading text (3 o'clock direction), and higher
values representing a counter-clockwise rotation. (i.e., a value
of 90 would result in bottom-to-top reading text).
fontfile is the path to the TrueType font
you wish to use.
text is the text string which may include
UTF-8 character sequences (of the form: { ) to access
characters in a font beyond the first 255.
col is the color index. Using the negative
of a color index has the effect of turning off antialiasing.
ImageTTFText returns an array with 8
elements representing four points making the bounding box of the
text. The order of the points is upper left, upper right, lower
right, lower left. The points are relative to the text
regardless of the angle, so "upper left" means in the top
left-hand corner when you see the text horizontallty.
This example script will produce a black GIF 400x30 pixels, with
the words "Testing..." in white in the font Arial.
ImageTTFText
<?php
Header("Content-type: image/gif");
$im = imagecreate(400,30);
$black = ImageColorAllocate($im, 0,0,0);
$white = ImageColorAllocate($im, 255,255,255);
ImageTTFText($im, 20, 0, 10, 20, $white, "/path/arial.ttf", "Testing... Omega: Ω");
ImageGif($im);
ImageDestroy($im);
?>
This function requires both the GD library and the FreeType library.
See also ImageTTFBBox.