Merge two images with transparencies in PHP

℡╲_俬逩灬. 提交于 2019-12-06 04:43:15

问题


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


来源:https://stackoverflow.com/questions/6458506/merge-two-images-with-transparencies-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!