How can one efficiently manage the color palette in PHP when working with GIF images to avoid memory limitations?

When working with GIF images in PHP, managing the color palette efficiently is crucial to avoid memory limitations. One way to do this is by reducing the number of unique colors in the image to optimize memory usage. This can be achieved by using functions like imagecolorstotal() and imagecolorclosest() to limit the color palette to a smaller set of colors without compromising the quality of the image.

// Open the GIF image
$gif = imagecreatefromgif('example.gif');

// Reduce the color palette to 256 colors
imagetruecolortopalette($gif, false, 256);

// Save the optimized GIF image
imagegif($gif, 'optimized.gif');

// Free up memory
imagedestroy($gif);