tags:

views:

587

answers:

3

I need to flip an image so that a character faces in the right direction. This needs to be done "on the fly' as they say.

The issue I am having is that with Gif images, I seem to lose the transparency. (The background goes white)

Below is the code: (Alternatively someone could send me to a good example)

$img = imagecreatefromgif("./unit.gif");

$size_x = imagesx($img);
$size_y = imagesy($img);

$temp = imagecreatetruecolor($size_x, $size_y);

imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));
imagealphablending($img, false);
imagesavealpha($img, true);

$x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y);

if ($x) {
    $img = $temp;
}
else {
    die("Unable to flip image");
}

header("Content-type: image/gif");
imagegif($img);
imagedestroy($img);
A: 

If you can guarantee the presence of ImageMagick, you can use their mogrify -flop command. It preserves transparency.

Pi
+1  A: 

Shouldn't this:

imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));
imagealphablending($img, false);
imagesavealpha($img, true);

...be this:

imagecolortransparent($temp, imagecolorallocate($img, 0, 0, 0));
imagealphablending($temp, false);
imagesavealpha($temp, true);

Note you should be calling these functions for the $temp image you have created, not the source image.

Jim
+1  A: 

Final Results:

$size_x = imagesx($img);
$size_y = imagesy($img);

$temp = imagecreatetruecolor($size_x, $size_y);

imagecolortransparent($temp, imagecolorallocate($temp, 0, 0, 0));
imagealphablending($temp, false);
imagesavealpha($temp, true);
$x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y);
if ($x) {
    $img = $temp;
}
else {
    die("Unable to flip image");
}

header("Content-type: image/gif");
imagegif($img);
imagedestroy($img);
Markus