Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate a PNG then resave with Image Transparency

I'm having some major issues getting PNG transparency on a PNG that is being rotated.

$filename = 'bird_up.png';
$source = imagecreatefrompng($filename) or die('Error opening file '.$filename);
imagealphablending($source, false);
imagesavealpha($source, true);
$rotation = imagerotate($source, $degrees, imageColorAllocateAlpha($source, 0, 0, 0, 127));
imagealphablending($source, false);
imagesavealpha($source, true);
header('Content-type: image/png');
imagepng($rotation);
imagedestroy($source);
imagedestroy($rotation);
like image 810
John Rake Avatar asked Dec 12 '22 20:12

John Rake


1 Answers

I've added a working commented version below

<?php
// this file writes the image into the http response,
// so we cant have any output other than headers and the file data
ob_start();

$filename       = 'tibia.png';
$degrees        = 45;

// open the image file
$im = imagecreatefrompng( $filename );

// create a transparent "color" for the areas which will be new after rotation
// r=0,b=0,g=0 ( black ), 127 = 100% transparency - we choose "invisible black"
$transparency = imagecolorallocatealpha( $im,0,0,0,127 );

// rotate, last parameter preserves alpha when true
$rotated = imagerotate( $im, $degrees, $transparency, 1);

// disable blendmode, we want real transparency
imagealphablending( $rotated, false );
// set the flag to save full alpha channel information
imagesavealpha( $rotated, true );

// now we want to start our output
ob_end_clean();
// we send image/png
header( 'Content-Type: image/png' );
imagepng( $rotated );
// clean up the garbage
imagedestroy( $im );
imagedestroy( $rotated );

Demo Original image from Wikipedia

That's the original from wikipedia

rotated -45 degrees, new areas with ~50% opacity for a demo

$transparency = imagecolorallocatealpha( $im,0,0,0,55 );

rotated 45 degrees, new areas with ~50% opacity for a demo

rotated -45 degress, new areas with 100% opacity

$transparency = imagecolorallocatealpha( $im,0,0,0,127 );

rotated 45 degress, new areas with 100% opacity

like image 117
Michel Feldheim Avatar answered Jan 18 '23 21:01

Michel Feldheim