PHP 7.0.26 Released

imagecreatetruecolor

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagecreatetruecolorCreate a new true color image

Description

resource imagecreatetruecolor ( int $width , int $height )

imagecreatetruecolor() returns an image identifier representing a black image of the specified size.

Parameters

width

Image width.

height

Image height.

Return Values

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

Examples

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

<?php
header 
('Content-Type: image/png');
$im = @imagecreatetruecolor(12020)
      or die(
'Cannot Initialize new GD image stream');
$text_color imagecolorallocate($im2331491);
imagestring($im155,  'A Simple Text String'$text_color);
imagepng($im);
imagedestroy($im);
?>

The above example will output something similar to:

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

See Also

add a note add a note

User Contributed Notes 36 notes

up
21
Richard Davey rich at corephp dot co dot uk
10 years ago
If you want to create a *transparent* PNG image, where the background is fully transparent, and all draw operations happen on-top of this, then do the following:

<?php
    $png
= imagecreatetruecolor(800, 600);
   
imagesavealpha($png, true);

   
$trans_colour = imagecolorallocatealpha($png, 0, 0, 0, 127);
   
imagefill($png, 0, 0, $trans_colour);
   
   
$red = imagecolorallocate($png, 255, 0, 0);
   
imagefilledellipse($png, 400, 300, 400, 300, $red);
   
   
header("Content-type: image/png");
   
imagepng($png);
?>

What you do is create a true colour image, make sure that the alpha save-state is on, then fill the image with a colour that has had its alpha level set to fully transparent (127).

The resulting PNG from the code above will have a red circle on a fully transparent background (drag the image into Photoshop to see for yourself)
up
15
arthur at kuhrmeier dot com
7 years ago
HOW THE CHECK THE MEMORY BEFORE CREATING AN IMAGE?

I worked on a script where I delt with large images. Very often the error "out of memory" occured. So I had to figure out, how to check the memory BEFORE creating an image. I didn't find a solution on the web, so I ran my own test script. It built lots of images to compute the needed memory. I found out, that the formula mem = x * y * channel was not enough. There was an additional multiplier that varied. As a result 1.7 worked best. So the formula is: mem = x * y * channel * 1.7.

I post this script here hoping it is useful to someone who will run into the same problems.

<?php
//-------------------------------------------------- DEFINE MAXMEM
define ("MAXMEM", 32*1024*1024);  //--- memory limit (32M) ---

//-------------------------------------------------- ENOUGH MEMORY ?
function enoughmem ($x, $y, $rgb=3) {
    return (
$x * $y * $rgb * 1.7 < MAXMEM - memory_get_usage() );
}

//-------------------------------------------------- SIMPLE EXAMPLE
list ($x, $y) = @getimagesize ('your_img.jpg');  //--- get size of img ---
if (enoughmem($x,$y)) {
   
$img = @imagecreatefromjpeg ('your_img.jpg');  //--- open img file ---
   
$thumb = 200//--- max. size of thumb ---
   
if ($x > $y) {
       
$tx = $thumb//--- landscape ---
       
$ty = round($thumb / $x * $y);
    } else {
       
$tx = round($thumb / $y * $x);  //--- portrait ---
       
$ty = $thumb;
    }
    if (
enoughmem($tx,$ty)) {
       
$thb = imagecreatetruecolor ($tx, $ty);  //--- create thumbnail ---
       
imagecopyresampled ($thb,$img, 0,0, 0,0, $tx,$ty, $x,$y);
       
imagejpeg ($thb, 'your_thumbnail.jpg', 80);
       
imagedestroy ($thb);
    }
   
imagedestroy ($img);
}

//--------------------------------------------------
//--- to check the memory working with           ---
//--- b/w-image or gif use:                      ---
//--------------------------------------------------
$check = enoughmem ($x, $y, 1);
?>

Taking the opportunity, I thank everyone here at php.net for the great manual and the useful user scripts.
up
3
send at mail dot 2aj dot net
12 years ago
If you want a simple way to mirror images, use the function I've included below.

<?php
function image_mirror ($input_image_resource)
{
   
$width = imagesx ( $input_image_resource );
   
$height = imagesy ( $input_image_resource );
   
$output_image_resource = imagecreatetruecolor ( $width, $height );
   
$y = 1;

    while (
$y < $height )
    {
        for (
$i = 1; $i <= $width; $i++ )
           
imagesetpixel ( $output_image_resource, $i, $y, imagecolorat ( $input_image_resource, ( $i ), ( $height - $y ) ) );
       
$y = $y + 1;
    }
   
    return
$output_image_resource;
}
?>
Example Usage:
<?php

// A good use of this is when a user uploads a TGA file,
// on the completion screen show the image and have a link
// that asks if the image appears mirrored, and if so
// that link will execute these commands below.

// I suggest checking $HTTP_REFERER for security.

// $_GET['file'] in this case would be something along the lines
// of johndoe-img0001 (Basename is necessary to prevent
// abuse of this script!)

if ( isset( $_GET['file'] ) )
{
   
$filename = "./" . basename ( $_GET['file'] ) . ".jpg";
// Making the image resource that needs to be mirrored
// Taking it from a previously exported to JPEG file.
   
$output_resource_image = image_mirror ( imagecreatefromjpeg ( $filename ) );
    if (
imagejpeg ( $output_resource_image, $filename, 75 ) )
        echo
"Image resaved successfully";
    else
        echo
"Image couldn't be written over (Check permissions)!";
}
?>
up
6
jessiedeer at hotmail dot com
4 years ago
There is no need to allocate colors with imagecreatetruecolor. All [256 x 256 x 256 x 128] true colors are already allocated, and you can use the color indexes directly.

Examples :
Blue => color index 255.
White => color index 16777215 (= 255*256² + 255*256+255).
Full transparent => color index 2130706432 (= 127*256^3).
up
3
d dot duquenoy at kdland dot org
11 years ago
My function to know how much bytes imagecreate or imagecreatetruecolor require before using it.
<?php
function getNeededMemoryForImageCreate($width, $height, $truecolor) {
  return
$width*$height*(2.2+($truecolor*3));
}
?>
up
2
weareexit at yahoo dot co dot uk
9 years ago
If you want to place an image on a larger canvas you've previously created with imagecreatetruecolor(), but you don't want the default black background to surround it: use imagefill() AFTER imagecopyresampled().

I have no idea why this should be the case, but it works!
up
2
Anonymous
12 years ago
// Creates a transparent image rather than the default black image
function imageCreateTransparent($x, $y) {
    $imageOut = imagecreate($x, $y);
    $colourBlack = imagecolorallocate($imageOut, 0, 0, 0);
    imagecolortransparent($imageOut, $colourBlack);
    return $imageOut;
}
up
0
hemjesti at yahoo dot com
8 years ago
I put this together - combining two of the examples and then generated the text dynamically. but, with this set up, i was able to get the transparent background working as well.

<?php
// Set the content-type

header('Content-type: image/png');

// Create the image
$im = imagecreatetruecolor(175, 15);
imagesavealpha($im, true);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 25, $black);
$trans_colour = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $trans_colour);

// The text to draw
$text = $_GET['text'];
// Replace path by your own font path
$font = 'catriel regular.ttf';

// Add some shadow to the text
imagettftext($im, 9, 0, 13, 16, $black, $font, $text);

// Add the text
imagettftext($im, 9, 0, 12, 15, $white, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
up
0
kai at meder dot info
13 years ago
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
up
0
fixxxer at php5 dot ru
13 years ago
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
}
up
0
Justin Greer
14 years ago
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);
}
up
0
Hallvord RM Steen <phpnet at hallvord dot com>
14 years ago
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);

?>
up
0
Jami
14 years ago
It's good to use the imagecopyresampled- function when creating thumbnails with true colors, it might look better than imagecopyresized..
up
0
bjorntje at hotmail dot com
14 years ago
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));
up
0
Micke (micke dot prag at newstonight dot net)
14 years ago
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); }
up
0
Andreas from www.ems-p.de
14 years ago
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);
}
up
0
marc at thewebguys dot com dot au
14 years ago
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.
up
0
billet_jerome at yahoo dot fr
14 years ago
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;
}
up
0
aaron at aaron-wright dot com
15 years ago
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>";
up
0
eric at spiderws dot com
16 years ago
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
up
-2
Justin Greer
13 years ago
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.)
up
-2
php at REMOVEreallynicejerk dot com
15 years ago
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()
}
up
-1
behun at webconsult dot sk
11 years ago
imagecreatetruecolor() returns not only image identifier representing a black image of size x_size by y_size.

imagecreatetruecolor() is called to create truecolor images, with an essentially unlimited number of colors (also not only 256 colors).
up
-1
phpnet at sjeiti dot com
10 years ago
Just a small rectification for the msg by '
thomas dot urban at toxa dot de' (23-May-2006 03:28) about transparency.
Line 3 in the example returns a 'wrong parameter warning': 'imagecolorallocate' should be replaced by 'imagecolorallocatealpha'.
(You better just alter that note and delete this one.)
up
-1
Florin [ florin.at.flachi.dot.net ]
11 years ago
A very simple and efficient way to create RGB color from hexadecimal (HTML) notation:

<?php

   
function color_hex2dec ($color) {
        return array (
hexdec (substr ($color, 0, 2)), hexdec (substr ($color, 2, 2)), hexdec (substr ($color, 4, 2)));
    }

    list (
$r, $g, $b) = color_hex2dec ('FFEECC');

?>
up
-1
j.fenin _At_ seekport [d0t] biz
11 years ago
I had a strange bug occurring under Debian Linux with PHP5.

In file B (where I create the image) I included a file (file A). The image that was produced was always corrupt. When I did not include file A, everything was fine.

After 2 hours of searching I found that there were some extra spaces and linefeeds after the PHP closing tag ?> in file A. After removing those chars, everything works fine again.

Obviously those extra bytes of file A were added to the image and corrupted it.