search for in the  
<imagecreatefromxpmimagedashedline>
Last updated: Thu, 19 May 2005

imagecreatetruecolor

(PHP 4 >= 4.0.6, PHP 5)

imagecreatetruecolor -- Create a new true color image

Description

resource imagecreatetruecolor ( int x_size, int y_size )

imagecreatetruecolor() returns an image identifier representing a black image of size x_size by y_size.

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

<?php
header
("Content-type: image/png");
$im = @imagecreatetruecolor(50, 100)
     or die(
"Cannot Initialize new GD image stream");
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5"A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>

Note: This function requires GD 2.0.1 or later.

Note: This function will not work with GIF file formats.

See also imagedestroy() and imagecreate().



User Contributed Notes
imagecreatetruecolor
kuya1284 at techie dot com
27-Feb-2005 01:48
OverFlow636,

It appears that your code was causing TGA's to be inverted horizontally and upside down.  I modified your code accordingly. The sample below is an example of what I did to convert a tga to jpg. The for loop was taken from the comment below (Eric Mulders) to properly render the image.

Nice job with the code buddy.

function tga2jpg ($image)
{
   $handle = fopen($image, "rb");
   $data = fread($handle, filesize($image));
   fclose($handle);

   $pointer = 18;
   $w = fileint (substr ($data, 12, 2));
   $h = fileint (substr ($data, 14, 2));
   $x = 0;
   $y = $h;

   $img = imagecreatetruecolor($w, $h);

   while ($pointer < strlen($data))
   {
       imagesetpixel ($img, $x, $y, fileint (substr ($data, $pointer, 3)));
      
       $x++;

       if ($x == $w)
       {
           $y--;
           $x = 0;
       }

       $pointer += 3;
   }
  
   for($a = 0; $a < imagecolorstotal ($img); $a++)
   {
       $color = imagecolorsforindex ($img, $a);
          
       $R=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
       $G=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
       $B=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
          
       imagecolorset ($img, $a, $R, $G, $B);
   }
        
   imagejpeg ($img, 'test.jpg', 100);
   imagedestroy ($img);
}

function fileint($str)
{
   return base_convert (bin2hex (strrev ($str)), 16, 10);
}

tga2jpg ('test.tga');
OverFlow636 at gmail dot com
14-Dec-2004 02:14
i dont know if there was an easyer way to do this, but heres my code to convert a .tga image to whatever you want to output it as
it works with basic tga files only

<?
$handle
= fopen("xxx.tga","rb");
$data = fread($handle,filesize("xxx.tga"));
fclose($handle);
$pointer = 18;
$x = 0;
$y = 0;
$w = fileint(substr($data,12,2));
$h = fileint(substr($data,14,2));
$img = imagecreatetruecolor($w,$h);

while (
$pointer < strlen($data))
{
imagesetpixel($img, $x,$y,fileint(substr($data,$pointer,3)));
$x++;

if (
$x==$w)
{
$y++;
$x=0;
}

$pointer += 3;
}

header("Content-type: image/jpeg");
imagepng($img);
imagedestroy($img);

function
fileint($str)
{
  return
base_convert(bin2hex(strrev($str)),16,10);
}
?>
termian
05-Dec-2004 06:59
kai wrote:
//using imagecolorallocate to specify the image's background
//color does not work with truecolor-image.
//
//instead you have to use imagefill to force flood-filling the
//image with the backgorund-color previously allocated:
//
//$bgColor = imagecolorallocate($img, 255,255,255);
//imagefill($img , 0,0 , $bgColor);

even this doesn't work for my configuration - fedora core2, php 4.3.8 + gd bundled (2.0.23 compatible) and I have to do this:
$img = imagecreatetruecolor($x, $y);
$bgColor = imagecolorallocate($img, 255,255,255);
imagefilledrectangle($img, 0, 0, $x-1, $y-1, $bgColor);
kai at meder dot info
07-Oct-2004 11:20
using imagecolorallocate to specify the image's background color does not work with truecolor-image.

instead you have to use imagefill to force flood-filling the image with the backgorund-color previously allocated:

$bgColor = imagecolorallocate($img, 255,255,255);
imagefill($img , 0,0 , $bgColor);

kai
ernst at baschny dot de
23-Aug-2004 07:38
Depending on the PHP version you might need to perform different type of checks to see if this function is supported. Here is a list of how different PHP releases behave:

4.0.6 and 4.1.x: The function is always defined if the GD-module (any version!) is loaded. If called without having GD2.0, will return a "Fatal error" (and abort your script). No way to handle this

4.2.x: The function is always defined if the GD-module is loaded. If called without having GD2.0, will generate a PHP "Warning", your script will go on (without a valid resource)

4.3.x: The function is *only* defined if you have compiled PHP with GD2.0 and this module is loaded. Here you have the easiest method to detect if it works (function_exists).

Unfortunately, if you want to support 4.0.6, 4.1.x and 4.2.x you *will* have to check for current PHP-version and GD-version instead of relying on function_exists().
unigram at byair dot net
25-May-2004 04:46
If your hosting system does not have imagecreatetruecolor() because of PHP<4.2 and GD<2.0 then a get around is

<?
$thumb
= imagecreate ($width, $height);
imageJPEG($thumb,"images/temp.jpg");
$thumb = @imagecreatefromjpeg("images/temp.jpg");
?>

which creates a thumbnail of right size, saves as a jpeg and then reads it, in true color.

This corrected the degradation caused by using palette images as destination for imagecopyresized ()
unigram at byair dot net
01-Apr-2004 06:36
If your hosting system does not have imagecreatetruecolor() because of PHP<4.2 and GD<2.0 then a get around is

<?
$thumb
= imagecreate ($width, $height);
imageJPEG($thumb,"images/temp.jpg");
$thumb = @imagecreatefromjpeg("images/temp.jpg");
?>

which creates a thumbnail of right size, saves as a jpeg and then reads it, in true color.

This corrected the degradation caused by using palette images as destination for imagecopyresized ()
Justin Greer
08-Jan-2004 10:38
I know it's not a discussion board, but when incorrect info is posted, it should be corrected.

The function_exists() check does not work correctly because if PHP is compiled with an older GD library, the imagecreatetruecolor() function still exists -- it just gives a fatal error when called, stating that GD2 is required.  Therefore, the function_exists() method will fail on any new-ish copy of PHP that only has GD 1.x.  (That includes most of the 4.1.x and 4.2.x installs I've seen.)
fixxxer at php5 dot ru
26-Dec-2003 07:47
A note to post by Justin Greer @ 18-Nov-2003 10:40:

While this information has already been posted by php at REMOVEreallynicejerk dot com @ 16-Sep-2002 12:01, I feel it neccesary to notice 'cause Justin's post is in the top and it can make people go the wrong way: Justin's way of detecting which imagecreate function to use is too complicated, while there's an easy standard way:

<?php
if (function_exists('imagecreatetruecolor') {
 
// use imagecreatetruecolor
} else {
 
// use imagecreate
}
Justin Greer
18-Nov-2003 04:40
Unfortunately the @imagecreatetruecolor() method doesn't even work because php dies with a fatal error noting that GD 2 is required.  You can't even capture this error with a custom error handler.

I have come up with a function to get the GD version number that seems to work pretty well on every version of PHP and GD I've thrown at it (even CLI versions.)  It's obviously not the most efficient thing in the world, but it does cache the result in a static variable so calling it multiple times doesn't slow down further.

function gd_version() {
   static $gd_version_number = null;
   if ($gd_version_number === null) {
       // Use output buffering to get results from phpinfo()
       // without disturbing the page we're in.  Output
       // buffering is "stackable" so we don't even have to
       // worry about previous or encompassing buffering.
       ob_start();
       phpinfo(8);
       $module_info = ob_get_contents();
       ob_end_clean();
       if (preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i",
               $module_info,$matches)) {
           $gd_version_number = $matches[1];
       } else {
           $gd_version_number = 0;
       }
   }
   return $gd_version_number;
}

Then you can simply use it something like this:

if (gd_version() >= 2) {
   $image = ImageCreateTrueColor($width, $height);
} else {
   $image = ImageCreate($width, $height);
}
Hallvord RM Steen <phpnet at hallvord dot com>
27-Oct-2003 07:40
Regarding choosing the TrueColor or the plain version of imagecreate automatically, I've found that the following works for me:

<?php

$newImg
=@ImageCreateTrueColor($width, $height)
   or
$newImg=ImageCreate($width, $height);

?>
Jami
10-Jul-2003 05:11
It's good to use the imagecopyresampled- function when creating thumbnails with true colors, it might look better than imagecopyresized..
bjorntje at hotmail dot com
08-Jun-2003 12:41
I just fiddled around with Phpix, which had some problems using the GD lib
(washed out colours).
I changed the lines, which did the trick.
Just in case some of you are still having problems and
you can't change the PHP-install
on the hosting side:

$im = ImageCreateFromJPEG($source);
$new_im = ImageCreate($new_width,$new_height);
  
ImageCopyResized($new_im,$im,0,0,0,0,
$new_width,$new_height,ImageSX($im),ImageSY($im));

TO

$im = ImageCreateFromJPEG($source);
$new_im = ImageCreateTrueColor($new_width,$new_height);
  
ImageCopyResized($new_im,$im,0,0,0,0,$new_width,
$new_height,ImageSX($im),ImageSY($im));
Micke (micke dot prag at newstonight dot net)
08-Mar-2003 06:21
Here is my solution for creating images with the same code for both GD < 2 and GD > 2:

$dst_img = @imageCreateTrueColor($width, $height);
if (!$dst_img) { $dst_img = imageCreate($width, $height); }
Andreas from www.ems-p.de
28-Feb-2003 08:15
The request of gdlib from brad at brwebdesign dot com won't work with PHP < 4.1 (version_compare).

Some phpinfo versions offer the version number without space so you better ask for the dot:

ob_start();
phpinfo(8);
$phpinfo=ob_get_contents();
ob_end_clean();
$phpinfo=strip_tags($phpinfo);
$phpinfo=stristr($phpinfo,"gd version");
$phpinfo=stristr($phpinfo,"version");
$end=strpos($phpinfo,".");
$phpinfo=substr($phpinfo,0,$end);
$length = strlen($phpinfo)-1;
$phpinfo=substr($phpinfo,$length);
if($phpinfo<2){
   $dst_img=ImageCreate($new_w,$new_h);}
else {
   $dst_img=ImageCreateTrueColor($new_w,$new_h);
}
marc at thewebguys dot com dot au
24-Jan-2003 06:40
I discovered when installing GD 2+ that ImageCreate() doesn't work well with JPEGS, it makes a true colour JPEG into a 16 colour mess when combining ImageCreateFromJPEG(). If you have GD 2+ you must use ImageCreateTrueColor() for things like thumbnails, etc.
billet_jerome at yahoo dot fr
14-Jan-2003 07:26
Because imagecreatetruecolor exist both in gd and gd2,
you can't use function_exists or get_extension_funcs to check for gd2 !
But ... there is a difference in imagettfbbox between gd and gd2:
gd use pixels and gd2 use points.

Then you can check gd2 with this function:

function sysB_chkgd2()
{

$rep=false;
if(isset($GLOBALS["gBGDVersion"]))
   {
   $rep=$GLOBALS["gBGDVersion"];
   }
else
   {
   if(function_exists("gd_info"))
       {
       $gdver=gd_info();
       if(strstr($gdver["GD Version"],"1.")!=false)
         {
         $rep=false;
         }
       else
           {
           $rep=true;
           }
       }
   else
       {
       $size=40;
       $font= your font file path here;
       $b=imagettfbbox ($size,0,$font,"abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ");

       if(($size+1)<abs($b[5]-$b[3]))
           {
           $rep=true;
           }

         }
   $GLOBALS["gBGDVersion"]=$rep;
   }

return $rep;
}
aaron at aaron-wright dot com
25-Sep-2002 04:49
Actually GD <2.0 had imagecreattruecolor, it just didn't work :P

This is a better test:

function chkgd2(){
  $testGD = get_extension_funcs("gd"); // Grab function list
  if (!$testGD){ echo "GD not even installed."; exit; }
  if (in_array ("imagegd2",$testGD)) $gd_version = "<2"; // Check
  if ($gd_version == "<2") return false; else return true;
}

if (chkgd2()) echo "<h1>GD2+ is installed.</h1>"; // Test for GD2
else echo "<h1>GD2+ is not installed.</h1>";
php at REMOVEreallynicejerk dot com
15-Sep-2002 06:01
Why not just use function_exists? 

http://www.php.net/function_exists

Just because they have version 2.0 GD doesn't mean that they haven't disabled that function.

Also instead of determining which one you have on your machine and then writing setup specific code, you can write a universal code usable on either setups.

::pseudo code::

if (function_exists(imagecreatetruecolor)){
use imagecreatetruecolor()
}else{
use imagecreate()
}
brad at brwebdesign dot com
25-May-2002 04:26
I came up with this today.  You need GD2.0 or greater to use imagecreatetruecolor so you can parse phpinfo to get the needed information.  this will have to go at the very top of the page with no whitespace above it

<?php
ob_start
();
phpinfo(8);
$phpinfo=ob_get_contents();
ob_end_clean();
$phpinfo=strip_tags($phpinfo);
$phpinfo=stristr($phpinfo,"gd version");
$phpinfo=stristr($phpinfo,"version");
$end=strpos($phpinfo," ");
$phpinfo=substr($phpinfo,0,$end);
$phpinfo=substr($phpinfo,7);
if(
version_compare("2.0", "$phpinfo")==1)
echo
"you have a version less then 2";
?>

The if statement is for PHP 4.1 or greater, but you can use other methods of comparing the version numbers if the server you are on do not have that version of php
shwan at korea dot com
19-Mar-2002 01:14
If you upagrade the GD from 1.8.X to 2.0.X, you should delete config.cache before reconfigure the php source.
pmas7354 at artax dot karlin dot mff dot cuni dot cz
26-Feb-2002 07:40
Here is answer for first question 'why do I need true color images'.

True color images you need when you want to work with images such as photos (snapshots), video frames and so on.

When you need to combine some these images for user, or to send him only small part of your image, and you try to use 256 colors, image will be ugly (try it if you want). Some colors will change dramatically.

"Antialias" lines which you may see are probably the result of using JPEG compression. JPEG is not looseless compression so "small image details may be changed" in order to reduce image size dramatically. On really true-color images such as your snapshots of landscape and so on and using small compression level you will hardly see differences. But on exact objects, such as lines, circles, which you draw on solid background using single color, you can see that if you save and load this image that some details are changed.
rossa at studioware dot net
23-Jan-2002 09:38
function ConvertGreyscale($image){
# this file outputs a grey version of specified image

  $total = ImageColorsTotal($image);
  for( $i=0; $i<$total; $i++){
     $old = ImageColorsForIndex($image, $i);
    
     #trying to keep proper saturation when converting
     $commongrey = (int)(($old[red] + $old[green] + $old[blue]) / 3);

     ImageColorSet($image, $i, $commongrey, $commongrey, $commongrey);
  }
}
eric at spiderws dot com
12-Aug-2001 12:45
This little function does it for you:

<?
$image_id
= imageCreateFromJPEG($image);
for(
$a=0;$a<imagecolorstotal ($image_id);$a++)
       {
          
$color = ImageColorsForIndex($image_id,$i);
          
$R=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
          
$G=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
          
$B=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
          
ImageColorSet($image_id, $a, $R, $G, $B);
       }
imageJPEG($image_id,"$image");
?>

The .299 , .578 , .114 values are estimations, and add a gamma correction to the colors. For more or less luminace in the result, you can change these values.

Goodluck,
Eric Mulders, Netherlands
steve at stevegodwin dot com
30-Jun-2001 07:22
ImageCreateTrueColor is used to create an image resource with an unlimited number of colors, which is useful when manipulating JPEG images, for example.

ImageCreate is used to create an image resource with a 256 color palette, sometimes called indexed color.

In previous versions, ImageCreate worked OK for manipulating JPEG images. But in experimenting with the Win32 version of PHP 4.0.6, which I think relies on the GD 2.0.1 lib beta, you have to use ImageCreateTrueColor to get accurate color results with JPEGs.

<imagecreatefromxpmimagedashedline>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT