I am trying to rotate an image with transparency.
This code works, except when it is an angle of 90°, 180°, 270° and 360°. With those degrees, I create a black background.
$grados = 90;
$width = 191;
$height = 65;
$logo = 'logo.png';
$resizeImagenNueva = 'nuevologo.png';
//cambiar tamaño
$logo = imagecreatefrompng($logo);
$ximagen = imagesx($logo);
$yimagen = imagesy($logo);
$nuevoBlanco = imagecreatetruecolor($width, $height);
transparenteImagen($nuevoBlanco, $width, $height);
//copiar imagen
imagecopyresampled($nuevoBlanco, $logo, 0, 0, 0, 0, $width, $height, $ximagen, $yimagen);
imagepng($nuevoBlanco, $resizeImagenNueva);
//rotar
$imagenAlRotar = imagecreatefrompng($resizeImagenNueva);
$nuevoBlanco = imagecreatetruecolor($width, $height);
$transparenteRotate = transparenteImagenRotada($nuevoBlanco);
$rotar = imagerotate($nuevoBlanco, $grados, $transparenteRotate);
imagepng($rotar, $imagenRotada);
imagedestroy($imagenAlRotar);
function transparenteImagenRotada ($imagen)
{
imagealphablending($imagen, false);
imagesavealpha($imagen, true);
$transparente = imagecolorallocatealpha($imagen, 0, 0, 0, 127);
imagefill($imagen , 0, 0, $transparente);
return $transparente;
}
function transparenteImagen ($imagen, $width, $height)
{
imagealphablending($imagen, false);
imagesavealpha($imagen, true);
$transparente = imagecolorallocatealpha($imagen, 255,255,255, 127);
imagefilledrectangle($imagen, 0, 0, $width, $height, $transparente);
}
How can I rotate an image respecting the transparent background for any angle?
Rotate an image with a transparent background
Once the image is provided as a resource of type GD , the image can be easily rotated with the imagerotate function :
The only important point to consider is that when you rotate an image, blending occurs in the transformation. It is logical that it happens with each color in each pixel, but it is necessary to make sure that the values for the alpha channel (which establishes the transparency) are not mixed. For both the source and the destination, you must configure:
Code
Result