Merge two images with transparencies in PHP

2020-07-18 03:07发布

问题:

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:

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

回答1:

Do not use imagecopymerge() for merge transparent image.

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



回答2:

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);