<p>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. </p>

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

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

<pre><code>$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);
</code></pre>

[{'answer_id': 66574, 'author': 'Alex M', 'author_id': 9652, 'author_profile': 'https://Stackoverflow.com/users/9652', 'pm_score': 1, 'selected': False, 'text': '<p>If you can guarantee the presence of ImageMagick, you can use their <code>mogrify -flop</code> command. It preserves transparency.</p>\n'}, {'answer_id': 66586, 'author': 'Jim', 'author_id': 8427, 'author_profile': 'https://Stackoverflow.com/users/8427', 'pm_score': 3, 'selected': True, 'text': "<p>Shouldn't this:</p>\n\n<pre><code>imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));\nimagealphablending($img, false);\nimagesavealpha($img, true);\n</code></pre>\n\n<p>...be this:</p>\n\n<pre><code>imagecolortransparent($temp, imagecolorallocate($img, 0, 0, 0));\nimagealphablending($temp, false);\nimagesavealpha($temp, true);\n</code></pre>\n\n<p>Note you should be calling these functions for the $temp image you have created, not the source image.</p>\n"}, {'answer_id': 66765, 'author': 'Markus', 'author_id': 2490, 'author_profile': 'https://Stackoverflow.com/users/2490', 'pm_score': 2, 'selected': False, 'text': '<p>Final Results:</p>\n\n<pre><code>$size_x = imagesx($img);\n$size_y = imagesy($img);\n\n$temp = imagecreatetruecolor($size_x, $size_y);\n\nimagecolortransparent($temp, imagecolorallocate($temp, 0, 0, 0));\nimagealphablending($temp, false);\nimagesavealpha($temp, true);\n$x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y);\nif ($x) {\n    $img = $temp;\n}\nelse {\n    die("Unable to flip image");\n}\n\nheader("Content-type: image/gif");\nimagegif($img);\nimagedestroy($img);\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/66518', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2490/']