Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Image Functions : imagecreate

imagecreate

Create a new palette based image (PHP 4, PHP 5)
resource imagecreate ( int width, int height )

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

We recommend the use of imagecreatetruecolor().

Parameters

width

The image width

height

The image height

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example999. 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);
imagedestroy($im);
?>

The above example will output something similar to:


Related Examples ( Source code ) » imagecreate
















Code Examples / Notes » imagecreate

foxlovr1

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 foxlovr1@cox.net or aquafox90@yahoo.com for comments/questions.


ortreum

Use image as javascript test
There are two files - an image and an executive file. The image is loaded if the JavaScript is enabled. After (!) the page is loaded $_SESSION['js'] + 0 is 0 or 1.
the image (js.img.php):
<?php
session_start();
$_SESSION['js'] = 1;
header('Content-type: image/gif');
imagegif($im = imagecreate(1, 1));
imagedestroy($im);
?>
the html file (file.php):
<html>
<head>
<!--
<script type="text/javascript">
var img = new Image();
img.src = "js.img.php";
</script>
-->
</head>
<body>
<?php
if ($_SESSION['js'] . '' == '') echo 'Not checked for JavaScript.';
else if ($_SESSION['js'] + 0 == 0) echo 'JavaScript is disabled.';
if ($_SESSION['js'] + 1 == 1) echo 'JavaScript is enabled.';
?>
</body>
</html>
There are much more hidden actions that you can do by "pictures".


info

To make the gd library available for Apache2/mod_php on Gentoo the following steps are required (and sufficient):
1) Add a USE flag for gd in "/etc/make.conf":
  USE="<other use flags> gd"
  A list of all of the USE flags can be found at: http://www.gentoo.org/dyn/use-index.xml
2) Re-emerge mod_php by executing "emerge mod_php"
3) Restart apache2 by executing "/etc/init.d/apache2 restart"
You need not uncomment the "extension=php_gd2.dll" line in "php.ini" as mentioned in a previous posting (since that line is only relevant for Windows).


pawka

To make the gd library available for Apache2/mod_php on Fedora Linux the following commands are required:
1) yum install php-gd
2) /etc/init.d/httpd restart


scottlindh pwnd

to install on UBUNTU do the following..
sudo apt-get install php5-gd
After installing the package I restarted the apache
sudo /etc/init.d/apache reload
goto love ubuntu...


php dot net

To create an image from a PSD file, you can use imagecreatefrompsd(). It is available for download here: http://www.kingsquare.nl/phppsdreader/ . It returns a resource like the other ImageCreateFrom - functions

dhkold

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:  admin@dhkold.com                */
/* 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;
}
?>


wouter

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


05-jan-2005 09:30

This is how you can create a thumbnail with maximum height and width. This way it will fit nicely in a gallery table. In this example $im is the source image
<?
//calculate thumb size
$ow = imagesx($im);
   $oh = imagesy($im);
$maxh = 100;
$maxw = 150;
$new_h = $oh;
$new_w = $ow;
if($oh > $maxh || $ow > $maxw){
      $new_h = ($oh > $ow) ? $maxh : $oh*($maxw/$ow);
      $new_w = $new_h/$oh*$ow;
}
//create dst image
$dst_img = ImageCreateTrueColor($new_w,$new_h);
//resize and copy image
ImageCopyResized($dst_img, $im, 0,0,0,0, $new_w, $new_h, ImageSX($im), ImageSY($im));
$function_image_new($dst_img,$galdir.$file);
?>


robert

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().


tc_

Small piece of code to display a preview of a file in an image (usefull for thumbnail view of a folder etc.)
<?php
$file = "test.txt"; //FILEADDRESS
$size = "100"; //IMAGE SIZE
$data = file($file);
$im = @ imagecreate($size, $size) or die();
$bc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
$lines = (int) $size / 10;
for ($t = 0; $t < $lines; $t++)
{
imagestring($im, 3, 4, 4, $data[$t], $tc);
imagestring($im, 3, 4, 4 + ($t * 10), $data[$t], $tc);
}
header("Content-type: image/png");
imagepng($im);
imagedestroy($im);
?>
Maybe it will be usefull for somebody.


rolf dot winterscheidt

Since I needed some time to get something on my screen, here a small example of creating graphics:
<html>
<head>
</head>
<body>
<?php
$pic=ImageCreate(600,600);
$col1=ImageColorAllocate($pic,200,200,200);
$col2=ImageColorAllocate($pic,0,0,255);
ImageFilledRectangle($pic,1,1,100,100,$col2);
ImagePNG($pic,"pic.png");
ImageDestroy($pic);
?>
<img src="pic.png" border=0>
</body>
</html>
--
You create a color for the background ($col1, seems to be zero for the background) and one for the boxcolor. The image will be written to disk as pic.png and you get it via normal html-command "img src"... That's it.
Rolf


removethisbeforebayet

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.


rupert

one thing i've noticed is that if, after creating the image, you don't wash it with a background colour, shapes you create on top will 'bleed' to fill the image.

sjnorrie

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.


scott

okay .. listen .. if you are getting fatal errors attempting to use ImageCreate() then you most probably do not have GD installed .. Likewise, if you are getting fatal errors attempting to use ImageGIF() then you are most probably using a version of GD which does not support the GIF format.  Notice that in both of these examples that the problem has nothing to do with PHP or whether or not PHP "supports" any particular function.  You must have the GD image library installed to make images work.  It is as simple as that.  Furthermore, although current versions of GD do NOT support the GIF format, I know that old versions of GD (ie. version 1.3) do support the GIF format but they are probably illegal to use now because of the fuss that unisys has been making about it.

tassader

It seems that imagecreate creates a grayscale image with gd2

sohel taslim

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);
}
?>


altype

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


kim

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


cstevens

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


tore

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!


andrus

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 :\

php

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 ;)


phantom

after some experimenting I've come to the following concusions:
1) if you don't have GD when compiling PHP you have to recompile PHP to enable GD support..
2) imagepng() works the same way as imagegif() just creates png's ..
3) the first color you imagecolormatch becomes the background.. hmm..
hope this helps anyone =)


kb2ici

A sample php image program to create a clock
<?php
header("Content-type: image/gif");
$imSize = 256;
$clockSize = $imSize - 8;
$today = getdate();
$hour = $today[hours];
$minutes = $today[minutes];
$seconds = $today[seconds];
if ($hour >= 12)
{
$hour -= 12;
}
$hourDegress = $hour * 30;
$hourDegress += $minutes / 2;
$minDegress = $minutes * 6;

//* the cordinate system stars at 3:00
$hourDegress -= 90;
if ($hourDegress < 0)
{
$hourDegress += 360;
}
$minDegress -= 90;
if ($minDegress < 0)
{
$minDegress += 360;
}

//* convert to radians
$hourRadians = $hourDegress / 57.295779513082;
$minRadians = $minDegress / 57.295779513082;

$myImage = ImageCreate($imSize, $imSize);

$white = ImageColorAllocate($myImage, 255, 255, 255);
$black = ImageColorAllocate($myImage, 0, 0, 0);
// $red = ImageColorAllocate($myImage, 255, 0, 0);
// $green = ImageColorAllocate($myImage, 0, 255, 0);
$blue = ImageColorAllocate($myImage, 0, 0, 255);
ImageFill($myImage, 0, 0, $blue);
Imageinterlace($myImage, 1);
//* draw the clock circle
Imagearc($myImage, $imSize/2, $imSize/2, $clockSize, $clockSize, 0, 359, $white);
//* draw the hour hand
$hourHandLen = ($clockSize / 2) * 0.6;
$x2 = $imSize/2 + ($hourHandLen * cos($hourRadians));
$y2 = $imSize/2 + ($hourHandLen * sin($hourRadians));
ImageLine($myImage, $imSize/2, $imSize/2, $x2, $y2, $white);
//* draw the minute hand
$minHandLen = ($clockSize / 2) * 0.9;
$x2 = $imSize/2 + ($minHandLen * cos($minRadians));
$y2 = $imSize/2 + ($minHandLen * sin($minRadians));
ImageLine($myImage, $imSize/2, $imSize/2, $x2, $y2, $white);
if ($minutes < 10)
{
$minutes = "0$minutes";
}
Imagestring($myImage, 3, 5, $imSize - 15, ($hour . ":" . $minutes), $white);
Imagegif($myImage);
Imagedestroy($myImage);

?>


help

// A simple XY graph
<html>
<head>
       
<title>XY Graph</title>
<h2>Practice XY Graph</h2>
</head>
<body>
<?php
$left = 0;
$top = 0;
$x_size = 400;
$y_size = 400;
$char_width = 8;
$char_height = 11;
$x_start = $x_left + 100;
$y_start = $top + $char_height * 1.5;
$x_end = $x_start + $x_size;
$y_end = $y_start + $y_size;
$right = $x_start + $x_size + 40;
$bottom = $y_start + $y_size + $char_height * 1.5;
$graph_n = 100;
for($i = 0; $i < $graph_n; $i++ )
   {
   $graph_x[$i] = $i;
   $graph_y[$i] = $i * $i;
   }
$min_x = 9e99;
$min_y = 9e99;
$max_x = -9e99;
$max_y = -9e99;
$avg_y = 0.0;

for($i = 0; $i < $graph_n; $i++ )
{
if( $graph_x[$i] < $min_x )
$min_x = $graph_x[$i];
if( $graph_x[$i] > $max_x )
$max_x = $graph_x[$i];
if( $graph_y[$i] < $min_y )
$min_y = $graph_y[$i];
if( $graph_y[$i] > $max_y )
$max_y = $graph_y[$i];
$avg_y += $graph_y[$i];
}

$avg_y = $avg_y / $graph_n;
$min_x = 0;
$min_y = 0;
$max_x += $max_x * 0.05;
$max_y += $max_y * 0.05;
$image = ImageCreate($right - $left, $bottom - $top);
$background_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 233, 14, 91);
$grey = ImageColorAllocate($image, 204, 204, 204);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$red = imagecolorallocate($image, 255, 0, 0);
imagerectangle($image, $left, $top, $right - 1, $bottom - 1, $black );
imagerectangle($image, $x_start, $y_start, $x_end, $y_end, $grey );
for($i = 0; $i < $graph_n; $i++ )
  {
  $pt_x = $x_start + ($x_end-$x_start)*($graph_x[$i]-$min_x)/($max_x-$min_x);
  $pt_y = $y_end - ($y_end - $y_start)*($graph_y[$i]-$min_y)/($max_y-$min_y);
//  imagesetpixel( $image, $pt_x, $pt_y, $black );
  imagechar($image, 2, $pt_x - 3, $pt_y - 10, '.', $black);
  }
$string = sprintf("%2.5f", $max_y);
imagestring($image, 4, $x_start - strlen($string) * $char_width, $y_start - $char_width, $string, $black);
$string = sprintf("%2.5f", $min_y);
imagestring($image, 4, $x_start - strlen($string) * $char_width, $y_end - $char_height, $string, $black);
$string = sprintf("%2.5f", $min_x);
imagestring($image, 4, $x_start - (strlen($string) * $char_width)/2, $y_end, $string, $black);

$string = sprintf("%2.5f", $max_x);
imagestring($image, 4, $x_end - (strlen($string) * $char_width) / 2, $y_end, $string, $black);
$x_title = 'x axis';
$y_title = 'y axis';
imagestring($image, 4, $x_start + ($x_end - $x_start) / 2 - strlen($x_title) * $char_width / 2, $y_end, $x_title, $black);
imagestring($image, 4, $char_width, ($y_end - $y_start) / 2, $y_title, $black);
header('Content-type: image/png');
$filename = sprintf("%d.png", time());
ImagePNG($image,$filename);
ImageDestroy($image);
printf("<img src='%s'> ", $filename);
?>
</body>
</html>


Change Language


Follow Navioo On Twitter
gd_info
getimagesize
image_type_to_extension
image_type_to_mime_type
image2wbmp
imagealphablending
imageantialias
imagearc
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
imagecreatefromgd2
imagecreatefromgd2part
imagecreatefromgd
imagecreatefromgif
imagecreatefromjpeg
imagecreatefrompng
imagecreatefromstring
imagecreatefromwbmp
imagecreatefromxbm
imagecreatefromxpm
imagecreatetruecolor
imagedashedline
imagedestroy
imageellipse
imagefill
imagefilledarc
imagefilledellipse
imagefilledpolygon
imagefilledrectangle
imagefilltoborder
imagefilter
imagefontheight
imagefontwidth
imageftbbox
imagefttext
imagegammacorrect
imagegd2
imagegd
imagegif
imagegrabscreen
imagegrabwindow
imageinterlace
imageistruecolor
imagejpeg
imagelayereffect
imageline
imageloadfont
imagepalettecopy
imagepng
imagepolygon
imagepsbbox
imagepsencodefont
imagepsextendfont
imagepsfreefont
imagepsloadfont
imagepsslantfont
imagepstext
imagerectangle
imagerotate
imagesavealpha
imagesetbrush
imagesetpixel
imagesetstyle
imagesetthickness
imagesettile
imagestring
imagestringup
imagesx
imagesy
imagetruecolortopalette
imagettfbbox
imagettftext
imagetypes
imagewbmp
imagexbm
iptcembed
iptcparse
jpeg2wbmp
png2wbmp
eXTReMe Tracker