Jump to content

Transparent background/pixels with GD


hlstriker

Recommended Posts

I'm trying to make pixels fully transparent so you can see the web page background bleed through the image.

 

The test I'm using is to make a gradient so it slowly fades to red.

 

Here is the code I'm using:

<?php
$width = 400;
$height = 400;

$png = imagecreatetruecolor($width, $height);

$numPixels = $width * $height;
$alphaPercent = 127 / $numPixels;
$a = 0;
for($y=0; $y<$height; $y++)
{
	for($x=0; $x<$width; $x++)
	{
		$alphaValue = ($numPixels - $a) * $alphaPercent;

		$color = imagecolorallocatealpha($png, 255, 0, 0, $alphaValue);
		imagesetpixel($png, $x, $y, $color);

		$a++;
	}
}

header('Content-type: image/png');
imagepng($png);
imagedestroy($png);
?>

 

The problem with this is instead of showing the web page background, it shows a black background on the image.

 

I made an example in Photoshop to give you a better understanding of what I'm trying to accomplish.

 

What I want: http://hldevs.com/indexalpha/testtransparent.html

What I have: http://hldevs.com/indexalpha/redtest.php

Link to comment
https://forums.phpfreaks.com/topic/141540-transparent-backgroundpixels-with-gd/
Share on other sites

I think you both misunderstood my question.

 

If you look in the example I made in Photoshop you will see the transparency bleeds through to the web page.

 

Now if you look at the example I made with PHP GD you will see the pixels are indeed transparent, but they don't bleed through to the web page; they are only transparent enough to see the default images black background.

 

EDIT:

I figured out that I had to use:

imagealphablending($png, false);

imagesavealpha($png, true);

 

Here is the final code:

<?php
$width = 400;
$height = 400;

$png = imagecreatetruecolor($width, $height);
imagealphablending($png, false);
imagesavealpha($png, true);

$numPixels = $width * $height;
$alphaPercent = 127 / $numPixels;
$a = 0;
for($y=0; $y<$height; $y++)
{
	for($x=0; $x<$width; $x++)
	{
		$alphaValue = ($numPixels - $a) * $alphaPercent;

		$color = imagecolorallocatealpha($png, 255, 0, 0, $alphaValue);
		imagesetpixel($png, $x, $y, $color);

		$a++;
	}
}

header('Content-type: image/png');
imagepng($png);
imagedestroy($png);
?>

 

And here is an example of the output:

http://hldevs.com/indexalpha/testtransparent_good.html

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.