Fill png transparency with background color

Viewed 1048

I'm refactoring an old image crop/resize library i wrote about 5 years ago and i'm stuck trying to restore one of it's functionalities. The funny part is that i'm not even sure it worked back then since i probably never actually used it.

I need to be able to work on png images while keeping transparency (which works), but i also wan't to be able to fill the transparent part of the image with a color.

Creating a blank image and filling it with a color works fine, but when i try to paste my png over it, the background is transparent again.

Here's a simplified version of my code:

 <?php

$src = imagecreatefrompng($pathToSomePngFile);

imagealphablending($src, false);
imagesavealpha($src, true);

$output = imagecreatetruecolor($width, $height);

if ($backgroundColor) {
    $fillColor = imagecolorallocate(
        $output, 
        $backgroundColor['r'], 
        $backgroundColor['g'], 
        $backgroundColor['b']
    );

    imagefilledrectangle(
        $output, 
        0, 
        0, 
        $width, 
        $height, 
        $fillColor
    );
} else {
    imagealphablending($output, false);
    imagesavealpha($output, true);
}

imagecopyresampled(
    $output,
    $src,
    0,
    0,
    0,
    0,
    $width,
    $height,
    $width,
    $height
);

imagepng($output, $pathToWhereImageIsSaved);

UPDATE

Updated with delboy1978uk's solution to get it to work without changing my other settings.

1 Answers

Something like this should work.

<?php

// open original image
$img = imagecreatefrompng($originalTransparentImage);
$width  = imagesx($img);
$height = imagesy($img);

// make a plain background with the dimensions
$background = imagecreatetruecolor($width, $height);
$color = imagecolorallocate($background, 127, 127, 127); // grey background
imagefill($background, 0, 0, $color);

// place image on top of background
imagecopy($background, $img, 0, 0, 0, 0, $width, $height);

//save as png
imagepng($background, '/path/to/new.png', 0);
Related