Search code examples
phptransparencyimage-rotationbounding-box

Black background in the bounding box created when an image is rotated with PHP


I've scoured the internet in search for an answer to this, but I cannot seem to find something that works. When I rotate an image, say, 5 degrees, that image is rotated within a boundary image that is created to house the rotation. That created image is completely black.

I'm trying to make it so that the bounding box image is completely transparent. Some of the other websites and questions I've looked at say that this should work:

<?PHP
$png = imagecreatefrompng('polaroids/polaroid0002.png');

// Do required operations
$png = imagerotate($png, 354.793, 0, 0);

// Turn off alpha blending and set alpha flag
imagealphablending($png, false);
imagesavealpha($png, true);

// Output image to browser
header('Content-Type: image/png');

imagepng($png);
imagedestroy($png);
?>

However, that yields this:

yields

What can I do for the black bounding box to be transparent?

Thanks!


Solution

  • Just set a transparent colour imagecolorallocatealpha($png, 0, 0, 0, 127) for background color.

    <?php
    $png = imagecreatefrompng('polaroids/polaroid0002.png');
    
    // Do required operations
    $png = imagerotate($png, 354.793, imagecolorallocatealpha($png, 0, 0, 0, 127), 0);
    
    // Turn off alpha blending and set alpha flag
    imagealphablending($png, false);
    imagesavealpha($png, true);
    
    // Output image to browser
    header('Content-Type: image/png');
    
    imagepng($png);
    imagedestroy($png);
    ?>