Q: Changing Black to Transparent in PHP I'm trying to replace the black background from gif/jpeg files with a transparent background, and because it's so tiring to manually do this one by one via PhotoShop, I thought of trying to use PHP. This is the code I'm using, but it doesn't work.
Why is that?
$image = imagecreatefromgif( 'items/item_spear06.gif' );
imagealphablending($image, true);
$transparentcolour = imagecolorallocate($image, 0,0,0);
imagecolortransparent($image, $transparentcolour);

And the image I got was just the same image as last time just in png format.

Update
$image = imagecreatefromgif( 'items/sword/iv_sword_refined19.gif' );

//get pixel data
$rgb = imagecolorat($image, 10, 10);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;

$index = imagecolorexact($image, $r, $g, $b); 
if ($index === -1) {
    $index = imagecolorallocate($image, $r, $g, $b);
}
imagecolortransparent($image, $index);

var_dump($r, $g, $b);

// Save the image
imagepng($image, 'imagecolortransparent.png');
imagedestroy($image);

Now var_dump returns: int(0) int(0) int(0) when it should be int(4) int(2) int(4)

A: I'm a little bit out on a whim here but I guess that the color you have chosen here (black) already exists in the palette. So, what we do is to try to find that color in the palette and set that one to transparent, if it does not exist, then we can use imagecolorallocate
$image = imagecreatefromgif( 'items/item_spear06.gif' );
$index = imagecolorexact($image, 0, 0, 0); 
if ($index === -1) {
    $index = imagecolorallocate($image, 0, 0, 0);
}
imagecolortransparent($image, $index);

To get the top-left pixels color
$index = imagecolorat($image, 0, 0);
$rgb = imagecolorsforindex($image, $index);

