PHPのお勉強!

PHP TOP

imagecreatetruecolor

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

imagecreatetruecolorTrueColor イメージを新規に作成する

説明

imagecreatetruecolor(int $width, int $height): GdImage|false

imagecreatetruecolor() は、指定した大きさの黒い画像を表す画像オブジェクトを返します。

パラメータ

width

画像の幅。

height

画像の高さ。

戻り値

成功した場合に画像オブジェクト、エラー時に false を返します。

変更履歴

バージョン 説明
8.0.0 成功時には、 この関数は GDImage クラスのインスタンスを返すようになりました。 これより前のバージョンでは、 resource を返していました。

例1 新規 GD イメージストリームの作成およびイメージの出力

<?php
header
('Content-Type: image/png');
$im = @imagecreatetruecolor(120, 20)
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);
?>

上の例の出力は、 たとえば以下のようになります。

出力例 : 新規 GD イメージストリームの作成およびイメージの出力

参考

add a note

User Contributed Notes 36 notes

up
32
Richard Davey rich at corephp dot co dot uk
17 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
20
arthur at kuhrmeier dot com
14 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
6
kai at meder dot info
20 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
7
Anonymous
19 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
3
aaron at aaron-wright dot com
22 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
4
jessiedeer at hotmail dot com
11 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
4
d dot duquenoy at kdland dot org
18 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
3
weareexit at yahoo dot co dot uk
16 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
send at mail dot 2aj dot net
19 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
3
Jami
21 years ago
It's good to use the imagecopyresampled- function when creating thumbnails with true colors, it might look better than imagecopyresized..
up
1
fixxxer at php5 dot ru
20 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
1
marc at thewebguys dot com dot au
21 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
2
Hamza Ahmad
3 years ago
As of PHP 8, the return type for image creation functions is GdImage instead of a resource. Therefore, people can type hint.
<?php
class MyImage {
private
GdImage $img;
};
?>
Similarly, <?php
function save_image(GdImage $img, string $name, string $directory = null) : bool
{
/*...*/
};
?>
up
1
eric at spiderws dot com
23 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
0
Florin [ florin.at.flachi.dot.net ]
18 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
0
j.fenin _At_ seekport [d0t] biz
18 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.
up
0
Justin Greer
20 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
0
Justin Greer
21 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