PHPverse 2025

Voting

: zero minus zero?
(Example: nine)

The Note You're Voting On

Darren Edale
11 years ago
The issue with filling using a rectangle is caused in your code by having alpha blending turned on before rendering the filled rectangle. Alpha blending causes what you draw on the image to be blended with whatever is already on the image according to the alpha channels of each. Therefore, because blending is on, and because the rectangle's fill colour is completely transparent, the blending of the existing image content with the transparent rectangle results in no change to the existing image.

With blending off, when drawing to the image what you draw completely replaces what is already there. So, drawing the rectangle in this case results in the original content of the image being completely replaced with a transparent rectangle.

So in order to use imagefilledrectangle() to erase an image to transparency, you need to turn off alpha blending first.

I guess the reason imagefill() works with alpha blending on is because it does not perform any alpha blending - it always works without alpha blending regardless of the setting. I suspect there are reasons for this to do with alpha channels complicating edge detection.

I would recommend using imagefilledrectangle() to create a blank transparent image resource instead of imagefill() because it is undoubtedly much faster in probably all cases.

Here is some example code to blank an image to transparent, assuming $im is a successfully created image:

<?php
$transparent
= imagecolorallocatealpha($im, 0, 0, 0, 127);
imagealphablending($im, false);
imagefilledrectangle($im, 0, 0, imagesx($im) - 1, $imagesy($im) - 1, $transparent);
imagecolordeallocate($transparent);
imagealphablending($im, true);
?>

<< Back to user notes page

To Top