Casey Flynn
Casey Flynn

Reputation: 14038

Merge two images with transparencies in PHP

I'm attempting to make a composite image of several .png's with background transparencies via php and store the resulting image in my database. My problem is that the transparent sections of my images are being dropped when I merge the images.

This is my code to create the composite image:

    $base = imagecreatefrompng('application/assets/images/vel1_bg.png');
    imagealphablending($base, true);
    list($baseWidth, $baseHeight, $type, $attr) = getimagesize('application/assets/images/vel1_bg.png');

    $user_board_items = $this->config->item('user_board_items');

    foreach($array as $key => $value){
        $item = imagecreatefrompng('application/assets/images/items/' . $user_board_items[$value[0]] . '.png');         
        imagealphablending($item, true);
        list($width, $height, $type, $attr) = getimagesize('application/assets/images/items/'. $user_board_items[$value[0]] . '.png');

        imagecopymerge($base,
                    $item,
                    floor(($value[1] / 100) * $baseWidth),
                    floor(($value[2] / 100) * $baseHeight),
                    0,
                    0,
                    $width,
                    $height,
                    100);
        imagedestroy($item);
    }

    //We have to capture the output buffer
    ob_start();
    imagepng($base);
    $baseimg = ob_get_clean();

This produces an image like this: enter image description here

And I'm looking for something more like this: enter image description here (Note how the transparent sections are represented)

Upvotes: 5

Views: 3241

Answers (2)

PepeNietnagel
PepeNietnagel

Reputation: 239

As mentioned before, imagecopyresampled worked for me as well after hours of trying different solutions. The parameters to be passed remain the same, except you have to remove the last one, but add source width and height. Your call would probably be:

  imagecopyresampled($base,
                $item,
                floor(($value[1] / 100) * $baseWidth),
                floor(($value[2] / 100) * $baseHeight),
                0,
                0,
                $width,
                $height,
                $width,
                $height);

Upvotes: 1

8xx8
8xx8

Reputation: 66

Do not use imagecopymerge() for merge transparent image.

It's better to use imagecopyresampled() in your script.

Upvotes: 5

Related Questions