Php: rotate a gif and save the image, preserving transparency
Posted: Fri Sep 04, 2020 2:28 pm
This is the code that work fine:
imagecopyresampled, imagecopy, imagecopyresized, all returns the same result.
without rotate
// $rotate = imagerotate($new_image, $degrees,0);
then change imagegif($rotate,'./an_image.gif');
into imagegif($new_image,'./another_image.gif');
the resulting image is ok, what it lose is the bg matte (if there is applied)
Code: Select all
// GIF rotation preserving transparency
$source = imagecreatefromgif('./an_image.gif');
$degrees = 180;
$width = imagesx($source);
$height = imagesy($source);
$new_image = imagecreatetruecolor($width, $height);
$transparencyIndex = imagecolortransparent($source);
$transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255);
if ($transparencyIndex >= 0) {
$transparencyColor = imagecolorsforindex($source, $transparencyIndex);
}
$transparencyIndex = imagecolorallocate($new_image, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']);
imagefill($new_image, 0, 0, $transparencyIndex);
imagecolortransparent($new_image, $transparencyIndex);
imagecopyresampled($new_image, $source, 0, 0, 0, 0, $width, $height, $width, $height);
$rotate = imagerotate($new_image, $degrees,0);
imagegif($rotate,'./an_image.gif');
imagedestroy($source);
without rotate
// $rotate = imagerotate($new_image, $degrees,0);
then change imagegif($rotate,'./an_image.gif');
into imagegif($new_image,'./another_image.gif');
the resulting image is ok, what it lose is the bg matte (if there is applied)
Sometimes when you make a transparent GIF and place it in an environment with a background colour (e.g. on a web page) you find that an ugly border appears around the image. The example on the right shows a transparent image placed on a purple background. As you can see there is a thin but nasty edge to the image.
This happens because the edges of the image need to gently transition into the background colour. In this example Photoshop has assumed that the background will be white, so it has faded the edges towards white. To fix the problem you need to tell Photoshop to fade the colour towards the actual background that you will be using.
Save as Indexed ColorTo do this you need to use the matte feature. When you select "Save As" you will see a window like the one on the right. Select the Matte drop-menu, then select Custom. A colour-picker window will appear — enter the colour of your background.