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

search for in the

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

view this page in

Image Functions

Úvod

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.

With the exif extension, 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. The exif functions do not require the GD library.

Note: Read the requirements section about how to expand image capabilities to read, write and modify images. To read meta data of pictures taken by digital cameras you need the above mentioned exif extension.

Požiadavky

If you have the GD library (available at » http://www.libgd.org/) 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 and less than gd-2.0.28 support PNG, not GIF. GIF support was re-enabled in gd-2.0.28.

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 its codebase is better maintained and more stable.

Note: Support for GD 1.x has been removed as of PHP 6.0.0, which requires GD 2.0.33 or later.

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

Supported image formats
Image format Library to download Notes
gif   Only supported in GD versions older than gd-1.6 and newer than gd-2.0.28. Read-only GIF support is available with PHP 4.3.0 and the bundled GD-library. Write support is available since PHP 4.3.9 and PHP 5.0.1.
jpeg-6b » ftp://ftp.uu.net/graphics/jpeg/ When buliding the jpeg-v6b library (prior to building PHP) you must use the --enable-shared option in the configure step. If you do not, you will receive an error saying libjpeg.(a|so) not found when you get to the configure step of building PHP.
png » http://www.libpng.org/pub/png/libpng.html Only supported in GD versions greater than gd-1.6.
xpm » ftp://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:

Supported font libraries
Font library Download Notes
FreeType 1.x » http://www.freetype.org/ Support removed as of PHP 6.0.0
FreeType 2 » http://www.freetype.org/  
T1lib » ftp://sunsite.unc.edu/pub/Linux/libs/graphics/) Support for Postscript Type 1 fonts.

Inštalácia

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. GD library requires libpng and libjpeg to compile.

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.

Supported image formats
Image Format Configure 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.

Note: When compiling PHP with libpng, you must use the same version that was linked with the GD library.

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

Supported font libraries
Font library Configure 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 (Postscript 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 Konfigurácia

Správanie tejto funkcie je ovplyvnené nastaveniami v php.ini.

Image Konfiguračné voľby
Názov Východzí Zamenitelný Changelog
gd.jpeg_ignore_warning "0" PHP_INI_ALL Available since PHP 5.1.3.
Pre ďalšie detaily a definície PHP_INI_* konštánt, si pozrite Zoznam php.ini direktív jadra.

Tu je krátke vysvetlenie konfiguračných direktív.

gd.jpeg_ignore_warning bool

Ignore warnings created by jpeg2wbmp() and imagecreatefromjpeg()

See also the exif configuration directives.

Warning

Image functions are very memory intensive. Be sure to set memory_limit high enough.

Typy zdrojov

This extension defines two resource types: an image identifier and a font identifier.

Preddefinované Konštanty

Konštanty uvedené nižšie sú definované týmto rozšírením a budú dostupné iba keď rozšírenie bolo buď kompilované do PHP alebo dynamicky načítané za behu (runtime).

GD_VERSION (string)
The GD version PHP was compiled against. (Available as of PHP 5.2.4)
GD_MAJOR_VERSION (integer)
The GD major version PHP was compiled against. (Available as of PHP 5.2.4)
GD_MINOR_VERSION (integer)
The GD minor version PHP was compiled against. (Available as of PHP 5.2.4)
GD_RELEASE_VERSION (integer)
The GD release version PHP was compiled against. (Available as of PHP 5.2.4)
GD_EXTRA_VERSION (string)
The GD "extra" version (beta/rc..) PHP was compiled against. (Available as of PHP 5.2.4)
IMG_GIF (integer)
Used as a return value by imagetypes()
IMG_JPG (integer)
Used as a return value by imagetypes()
IMG_JPEG (integer)
Used as a return value by imagetypes()

Note: This constant has the same value as IMAGE_JPG

IMG_PNG (integer)
Used as a return value by imagetypes()
IMG_WBMP (integer)
Used as a return value by imagetypes()
IMG_XPM (integer)
Used as a return value by imagetypes()
IMG_COLOR_TILED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_STYLED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_BRUSHED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_STYLEDBRUSHED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_TRANSPARENT (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_ARC_ROUNDED (integer)
A style constant used by the imagefilledarc() function.

Note: This constant has the same value as IMG_ARC_PIE

IMG_ARC_PIE (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_CHORD (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_NOFILL (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_EDGED (integer)
A style constant used by the imagefilledarc() function.
IMG_GD2_RAW (integer)
A type constant used by the imagegd2() function.
IMG_GD2_COMPRESSED (integer)
A type constant used by the imagegd2() function.
IMG_EFFECT_REPLACE (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_ALPHABLEND (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_NORMAL (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_OVERLAY (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_FILTER_NEGATE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_GRAYSCALE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_BRIGHTNESS (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_CONTRAST (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_COLORIZE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_EDGEDETECT (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_GAUSSIAN_BLUR (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_SELECTIVE_BLUR (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_EMBOSS (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_MEAN_REMOVAL (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_SMOOTH (integer)
Special GD filter used by the imagefilter() function.
IMAGETYPE_GIF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPEG (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_PNG (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_SWF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_PSD (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_BMP (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_WBMP (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_XBM (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_TIFF_II (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_TIFF_MM (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_IFF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JB2 (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPC (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JP2 (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPX (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_SWC (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_ICO (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions. (Available as of PHP 5.3.0)
PNG_NO_FILTER (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_NONE (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_SUB (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_UP (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_AVG (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_PAETH (integer)
A special PNG filter, used by the imagepng() function.
PNG_ALL_FILTERS (integer)
A special PNG filter, used by the imagepng() function.

Príklady

Example#1 PNG creation with PHP

<?php

header
("Content-type: image/png");
$string $_GET['text'];
$im     imagecreatefrompng("images/button1.png");
$orange imagecolorallocate($im22021060);
$px     = (imagesx($im) - 7.5 strlen($string)) / 2;
imagestring($im3$px9$string$orange);
imagepng($im);
imagedestroy($im);

?>
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



gd_info> <iis_stop_service
[edit] Last updated: Sun, 25 Nov 2007
 
add a note add a note User Contributed Notes Image
chuckstudios at gmail dot com 26-Nov-2008 05:18
I wrote a simple function to convert an image resource to PGM (portable graymap) in order to feed it to an OCR program. It works just like the rest of the image output functions, and will convert to grayscale for you:

<?php
   
function imagepgm($image, $filename = null)
    {
       
$pgm = "P5 ".imagesx($image)." ".imagesy($image)." 255\n";
        for(
$y = 0; $y < imagesy($image); $y++)
        {
            for(
$x = 0; $x < imagesx($image); $x++)
            {
               
$colors = imagecolorsforindex($image, imagecolorat($image, $x, $y));
               
$pgm .= chr(0.3 * $colors["red"] + 0.59 * $colors["green"] + 0.11 * $colors["blue"]);
            }
        }
        if(
$filename != null)
        {
           
$fp = fopen($filename, "w");
           
fwrite($fp, $pgm);
           
fclose($fp);
        }
        else
        {
            return
$pgm;
        }
    }
?>
dev at kingthief dot com 28-Mar-2008 04:20
I've developed a well-documented, fairly rock-solid API for creating on the fly, anti-aliased, rounded corner images, including full alpha transparency support for all you PNG lovers.

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

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

Installation is similar to PEAR.

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

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

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

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

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

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

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

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

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

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

    }

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

}

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

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

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

       
$var_1 = 2 * $L - $var_2;

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

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

}

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

?>
shd at earthling dot net 28-Mar-2006 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 )

?>
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($image, 0, $imgHeight-1, $imgWidth-1, $imgHeight-1, $colorGrey);

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

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

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

// Output graph and clear image from memory
imagepng($image);
imagedestroy($image);
?>
michal-ok at o2 dot pl 18-Oct-2005 09: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 09-Oct-2005 07:09
For fedora core 4 users that find that the gd library isn't installed, you can issue the command (as root)

# yum install php-gd

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

A sharpening example:

<?php

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

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

?>

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

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

<?php

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

UPCAbarcode('12345678901');

?>

 
show source | credits | sitemap | contact | advertising | mirror sites