Using imagecolorallocatealpha() to Allocate Colors with Alpha in PHP GD

This article explains how the PHP GD function imagecolorallocatealpha() assigns colors with transparency to an image, describes its parameters and return values, and provides a complete example that creates a PNG with overlapping circles using custom alpha values.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using imagecolorallocatealpha() to Allocate Colors with Alpha in PHP GD

The PHP function imagecolorallocatealpha() assigns a color with an alpha (transparency) value to an image resource, similar to imagecolorallocate() but with an extra $alpha parameter ranging from 0 (fully opaque) to 127 (fully transparent).

It returns the allocated color index on success, or FALSE (or a falsy non‑boolean) on failure.

The example creates a 300×300 true‑color image, allocates background and border colors, defines three overlapping circles with different colors and alpha levels, outputs the result as a PNG image, and finally destroys the image resource.

<?php
$size = 300;
$image = imagecreatetruecolor($size, $size);
// something to get a white background with black border
$back = imagecolorallocate($image, 255, 255, 255);
$border = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, $size-1, $size-1, $back);
imagerectangle($image, 0, 0, $size-1, $size-1, $border);
$yellow_x = 100;
$yellow_y = 75;
$red_x = 120;
$red_y = 165;
$blue_x = 187;
$blue_y = 125;
$radius = 150;
// allocate colors with alpha values
$yellow = imagecolorallocatealpha($image, 255, 255, 0, 75);
$red = imagecolorallocatealpha($image, 255, 0, 0, 75);
$blue = imagecolorallocatealpha($image, 0, 0, 255, 75);
// drawing 3 overlapped circle
imagefilledellipse($image, $yellow_x, $yellow_y, $radius, $radius, $yellow);
imagefilledellipse($image, $red_x, $red_y, $radius, $radius, $red);
imagefilledellipse($image, $blue_x, $blue_y, $radius, $radius, $blue);
// don't forget to output a correct header!
header('Content-Type: image/png');
// and finally, output the result
imagepng($image);
imagedestroy($image);
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendImage ProcessingPHPGDimagecolorallocatealpha
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.