GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Downloads
  • Documentation
  • Get Involved
  • Help
  • Getting Started
  • Introduction
  • A simple tutorial
  • Language Reference
  • Basic syntax
  • Types
  • Variables
  • Constants
  • Expressions
  • Operators

This view

  • Original page
  • New address

GeezerVison is showing www.php.net — PHP: imagecreate - Manual

PHP 8.6.0 RC5 available for testing
    imagecreatefromavif »
    « imagecopyresized
    • Preface
    • Function Reference
    • Image Processing and Generation
    • GD
    • GD and Image Functions

    imagecreate

    (PHP 4, PHP 5, PHP 7, PHP 8)

    imagecreate — Create a new palette based image

    Description

    function imagecreate(int $width, int $height): GdImage|false

    imagecreate() returns an image identifier representing a blank image of specified size.

    In general, we recommend the use of imagecreatetruecolor() instead of imagecreate() so that image processing occurs on the highest quality image possible. If you want to output a palette image, then imagetruecolortopalette() should be called immediately before saving the image with imagepng() or imagegif().

    Parameters

    width

    The image width.

    height

    The image height.

    Return Values

    Returns an image object on success, false on errors.

    Changelog

    Version Description
    8.0.0 On success, this function returns a GDImage instance now; previously, a resource was returned.

    Examples

    Example #1 Creating a new GD image stream and outputting an image.

    <?php
    header("Content-Type: image/png");
    $im = @imagecreate(110, 20)
        or die("Cannot Initialize new GD image stream");
    $background_color = imagecolorallocate($im, 0, 0, 0);
    $text_color = imagecolorallocate($im, 233, 14, 91);
    imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);
    imagepng($im);
    ?>

    The above example will output something similar to:

    Output of example : Creating a new GD image stream and outputting an image.

    See Also

    • imagecreatetruecolor() - Create a new true color image

    Found A Problem?

    Learn How To Improve This Page • Submit a Pull Request • Report a Bug
    +add a note

    User Contributed Notes 16 notes

    up
    down
    11
    DHKold ¶
    21 years ago
    to create an image from a BMP file, I made this function, that return a resource like the others ImageCreateFrom function:
    
    <?php
    /*********************************************/
    /* Fonction: ImageCreateFromBMP              */
    /* Author:   DHKold                          */
    /* Contact:  [email protected]                */
    /* Date:     The 15th of June 2005           */
    /* Version:  2.0B                            */
    /*********************************************/
    
    function ImageCreateFromBMP($filename)
    {
     //Ouverture du fichier en mode binaire
       if (! $f1 = fopen($filename,"rb")) return FALSE;
    
     //1 : Chargement des ent?tes FICHIER
       $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
       if ($FILE['file_type'] != 19778) return FALSE;
    
     //2 : Chargement des ent?tes BMP
       $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
                     '/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
                     '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
       $BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
       if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
       $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
       $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
       $BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
       $BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
       $BMP['decal'] = 4-(4*$BMP['decal']);
       if ($BMP['decal'] == 4) $BMP['decal'] = 0;
    
     //3 : Chargement des couleurs de la palette
       $PALETTE = array();
       if ($BMP['colors'] < 16777216)
       {
        $PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
       }
    
     //4 : Cr?ation de l'image
       $IMG = fread($f1,$BMP['size_bitmap']);
       $VIDE = chr(0);
    
       $res = imagecreatetruecolor($BMP['width'],$BMP['height']);
       $P = 0;
       $Y = $BMP['height']-1;
       while ($Y >= 0)
       {
        $X=0;
        while ($X < $BMP['width'])
        {
         if ($BMP['bits_per_pixel'] == 24)
            $COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
         elseif ($BMP['bits_per_pixel'] == 16)
         {  
            $COLOR = unpack("n",substr($IMG,$P,2));
            $COLOR[1] = $PALETTE[$COLOR[1]+1];
         }
         elseif ($BMP['bits_per_pixel'] == 8)
         {  
            $COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
            $COLOR[1] = $PALETTE[$COLOR[1]+1];
         }
         elseif ($BMP['bits_per_pixel'] == 4)
         {
            $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
            if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
            $COLOR[1] = $PALETTE[$COLOR[1]+1];
         }
         elseif ($BMP['bits_per_pixel'] == 1)
         {
            $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
            if     (($P*8)%8 == 0) $COLOR[1] =  $COLOR[1]        >>7;
            elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
            elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
            elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
            elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
            elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
            elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
            elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
            $COLOR[1] = $PALETTE[$COLOR[1]+1];
         }
         else
            return FALSE;
         imagesetpixel($res,$X,$Y,$COLOR[1]);
         $X++;
         $P += $BMP['bytes_per_pixel'];
        }
        $Y--;
        $P+=$BMP['decal'];
       }
    
     //Fermeture du fichier
       fclose($f1);
    
     return $res;
    }
    ?>
    up
    down
    3
    wouter at rusman dot net ¶
    25 years ago
    to compile GD support on some linux distributions you have to include these with the ./configure command :
    --with=gd=/usr --with-jpeg=/usr --with-png=/usr --with-zlib=/usr
    
    (i had to include this on Redhat 6.1)
    this becase the libraries are in /usr/lib instead of /lib
    up
    down
    1
    Sohel Taslim ¶
    19 years ago
    It is easy and simple example to convert Text to Image with selected font. 
    It helps me to display Bangla text as image when users have no installed bangla font.
    
    I hope it can help you too!
    
    <?php
    //Kip the font file together or write proper location.
    makeImageF("Life in PHP.","CENTURY.TTF");
    
    function makeImageF($text, $font="CENTURY.TTF", $W=200, $H=20, $X=0, $Y=0, $fsize=18, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){
            
        $im = @imagecreate($W, $H)
            or die("Cannot Initialize new GD image stream");
            
        $background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]);        //RGB color background.
        $text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]);            //RGB color text.
                
        imagettftext($im, $fsize, $X, $Y, $fsize, $text_color, $font, $text);
        
        header("Content-type: image/gif");                
        return imagegif($im);
    }
    
    ?>
    up
    down
    0
    php at silisoftware dot com ¶
    24 years ago
    Don't try and create an image with a really large width and/or height. First, $width x $height is (at least) the bytes of memory that need to be allocated. Secondly, if you exceed the range of int for either parameter, Apache crashes (before allocating any memory).
    Don't ask how I figured this out ;)
    up
    down
    0
    robert at scpallas dot de ¶
    24 years ago
    The function ImageCreate() creates a PALETTE image.
    The function ImageCreateFromJPEG() creates a TRUE COLOR image.
    
    When you use GD 2.0 you will get an error when you try to use ImageCopy()
    with one True color image and one Palette image.
    
    Be sure to convert one of the images before using ImageCopy() or use ImageCreateTrueColor() instead of ImageCreate().
    up
    down
    -1
    altype at bellsouth dot net ¶
    25 years ago
    ImagePNG($pic,"./dir/pic.png"); 
    
    To save image as a file, I had to create a directory "dir" and CHMOD 777 to give read, write, and execute permission for everyone - or it wouldn't save it...
    up
    down
    -2
    JamesM ¶
    16 years ago
    doesnt ruin the image but adds display to the output.
    this will generate an image with a random color. if you like it you can use it because you have the RBG result too.
    <?php
    header("content-type:image/png");
    $im = imagecreate(100, 100);
    $a = sprintf('%04x',mt_rand(0, 65535));
    $b = sprintf('%04x',mt_rand(0, 65535));
    $c = sprintf('%04x',mt_rand(0, 65535));
    $white = imagecolorallocate($im,$a,$b,$c);
    imagepng($im);
    imagedestroy($im);
    echo "\n\n\n$a-$b-$c";
    ?>
    up
    down
    -4
    kim at kimmccall dot org ¶
    25 years ago
    How I fixed my "undefined function imagecreate()" problem:
    I was having the same problem many have reported where most of PHP worked but the gd functions didn't.  I'd installed the RedHat rpm php-4.0.1pl2.  It said (phpinfo.php) that it had been configured with the '--with-gd=shared' option.  In my /usr/lib directory, I had both libgd.so.1.8.3 and libgd.a.  I decided to compile with the static library instead, so I downloaded the sources and built with all the same configuration flags except that I used --with-gd=/usr.  Now my gd library works!!!
    up
    down
    -2
    tassader at xmail dot cz ¶
    23 years ago
    It seems that imagecreate creates a grayscale image with gd2
    up
    down
    -2
    tore at kyberheimen dot com ¶
    24 years ago
    GD UPGRADE PROBLEM:
    I used imagecreate with gd 1.6 to make resized images of big photos. Then, when using the same script on gd 2.0, the colors got all wrong.
    Using imagecreatetruecolor() fixed the problem!
    up
    down
    -4
    removethisbeforebayet at removethistooenseirb dot fr ¶
    25 years ago
    Pay attention to a problem I encountered.
    Png images created with the PHP function seems to be very badly recognised by old browsers, especially -well, mainly - by IE 4.0 (crash of the browser).
    I think this is probably due to the fact that, when IE 4.0 was released, the png format was either very recent, either not very used, because of the widespread jpeg and gif formats...
    So, if you plan to dynamically create images for a web site to be seen by IE 4.0 users, think of it...
    May'be the jpeg format will do the job better.
    up
    down
    -3
    sjnorrie at hotmail dot com ¶
    22 years ago
    On windows.
    
    When you get undefined function image* it means the gd library isnt being used. Check the php.ini file. Make sure the php_gd.dll isnt commented out. Restarting apache should result in the image functions working.
    up
    down
    -4
    cstevens at gencom dot us ¶
    22 years ago
    Here's how I resolved the "Fatal error: Call to undefined function: imagecreate()" error using Gentoo:
    
    1) add a USE flag for gdb in /etc/make.conf
      
       USE="3dnow avi [whatever else you have] gdb"
    
       Note: here's a list of all of the USE flags:
       http://www.gentoo.org/dyn/use-index.xml
    
    2) unmerged mod_php 
    
    *Note* It could take awhile to "remerge" as it may need to compile several dependancies...do this during not production hours and have a backup if you absolutely cannot have downtime
    
       emerge -C mod_php
    
    3) emerged mod_php
    
       emerge -p mod_php 
        # find out if it's going to take awhile
    
    4) edit /etc/php/apach2-php4/php.ini
         uncomment the "extension=php_gd2.dll" line
    
    5) Restart apache2
    
        /etc/init.d/apache2 restart
    
    Hope this helps!
    
    --
    Cooper Stevenson
    GenCom
    http://www.gencom.us
    up
    down
    -5
    marc at gutt dot it ¶
    11 years ago
    Based on DHKold's contribution I realized imagecreatefrombmp() to support all 1-, 4-, 8-, 16-, 24- und 32-Bit Bitmaps. Finally Fabien Ménager brought it to perfection for the project DOMPDF. Feel free to use it:
    https://code.google.com/p/dompdf/source/browse/trunk/dompdf/include/functions.inc.php?spec=svn504&r=504#551
    up
    down
    -5
    foxlovr1 at cox dot net ¶
    22 years ago
    You can set it up so you can write a text which is controled from the URL.
    
    Like this...
    
    <?php
    header("Content-type: image/png");
    $im = @imagecreate(128, 16) or die("Cannot Initialize new GD image stream");
    $bc = imagecolorallocate($im, 0, 255, 255);
    $tc = imagecolorallocate($im, 0, 0, 0);
    imagestring($im, 1, 4, 4,  $t, $tc);
    imagepng($im);
    imagedestroy($im);
    ?>
    
    Then when you use the image, use this...
    
    <img src="http://www.yourdomain.com/stuff/cool_image.php?t=Text">
    
    This will create an image with a cyan background, and in black text it will say "Text"
    
    EMail me at [email protected] or [email protected] for comments/questions.
    up
    down
    -4
    andrus at vnet dot ee ¶
    25 years ago
    Dont forget to use ImageDestoy after showed image. I forgot it, my webpage had about 15 pictures what was generated by GD and webserver died very fastly (server was Dual Xeon 900MHz and 4G RAM :[[ ). It died cos of not enough memory :\
    +add a note
    • GD and Image Functions
      • gd_​info
      • getimagesize
      • getimagesizefromstring
      • image_​type_​to_​extension
      • image_​type_​to_​mime_​type
      • image2wbmp
      • imageaffine
      • imageaffinematrixconcat
      • imageaffinematrixget
      • imagealphablending
      • imageantialias
      • imagearc
      • imageavif
      • imagebmp
      • imagechar
      • imagecharup
      • imagecolorallocate
      • imagecolorallocatealpha
      • imagecolorat
      • imagecolorclosest
      • imagecolorclosestalpha
      • imagecolorclosesthwb
      • imagecolordeallocate
      • imagecolorexact
      • imagecolorexactalpha
      • imagecolormatch
      • imagecolorresolve
      • imagecolorresolvealpha
      • imagecolorset
      • imagecolorsforindex
      • imagecolorstotal
      • imagecolortransparent
      • imageconvolution
      • imagecopy
      • imagecopymerge
      • imagecopymergegray
      • imagecopyresampled
      • imagecopyresized
      • imagecreate
      • imagecreatefromavif
      • imagecreatefrombmp
      • imagecreatefromgd
      • imagecreatefromgd2
      • imagecreatefromgd2part
      • imagecreatefromgif
      • imagecreatefromjpeg
      • imagecreatefrompng
      • imagecreatefromstring
      • imagecreatefromtga
      • imagecreatefromwbmp
      • imagecreatefromwebp
      • imagecreatefromxbm
      • imagecreatefromxpm
      • imagecreatetruecolor
      • imagecrop
      • imagecropauto
      • imagedashedline
      • imageellipse
      • imagefill
      • imagefilledarc
      • imagefilledellipse
      • imagefilledpolygon
      • imagefilledrectangle
      • imagefilltoborder
      • imagefilter
      • imageflip
      • imagefontheight
      • imagefontwidth
      • imageftbbox
      • imagefttext
      • imagegammacorrect
      • imagegd
      • imagegd2
      • imagegetclip
      • imagegetinterpolation
      • imagegif
      • imagegrabscreen
      • imagegrabwindow
      • imageinterlace
      • imageistruecolor
      • imagejpeg
      • imagelayereffect
      • imageline
      • imageloadfont
      • imageopenpolygon
      • imagepalettecopy
      • imagepalettetotruecolor
      • imagepng
      • imagepolygon
      • imagerectangle
      • imageresolution
      • imagerotate
      • imagesavealpha
      • imagescale
      • imagesetbrush
      • imagesetclip
      • imagesetinterpolation
      • imagesetpixel
      • imagesetstyle
      • imagesetthickness
      • imagesettile
      • imagestring
      • imagestringup
      • imagesx
      • imagesy
      • imagetruecolortopalette
      • imagettfbbox
      • imagettftext
      • imagetypes
      • imagewbmp
      • imagewebp
      • imagexbm
      • iptcembed
      • iptcparse
      • jpeg2wbmp
      • png2wbmp
    • Deprecated
      • imagedestroy
    You are visitor 01402503 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.