Unusual result when merging two transparent images

2019-05-21 06:14发布

问题:

Im wondering if I'm doing something wrong, or if this is as good a result as im going to get. Both PNGs on the left are 95x111. The image of the robot has a 5px or so padding of transparent pixels around it, but it seems to be causing problems when they merge?

 $avatar = imagecreatefrompng("../guy.png");
 $borderImg = imagecreatefrompng("../frame.png");

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

 imagecopyresampled($avatar,$borderImg,  0, 0, 0, 0, 95, 111,95, 111);
 imagepng($avatar, $newfilenameBig); 

Ive tried every combo of imagealphablending and imagesavealpha I can think of. When I set $avatar to imagesavealpa= true, then it doesnt even show the image as all, just the frame. Doesn't that seem strange? Is this as far as i'm gonna get using PHP GD?

UPDATE: The desired result can be achieved when both images are created manually in PS using 24 bit mode. Is there a way to do this using imagecopy or similar?

回答1:

Try the following code its working fine.


    $width = 95;
    $height = 111;

    $base_image = imagecreatefrompng("../guy.png");
    $top_image = imagecreatefrompng("../frame.png");

    imagesavealpha($top_image, false);
    imagealphablending($top_image, false);
    imagecopy($base_image, $top_image, 0, 0, 0, 0, $width, $height);
    imagepng($base_image, "merged.png");



回答2:

I think that Jaguar library which uses GD will help to do that easily:

for example to create what you want you need to use the overlay action which works with gif,png,jpeg and any supported format:

Note This action is super fast and is not pixel based and the overlay could be any supported format and the opacity will be saved

use Jaguar\Canvas,
    Jaguar\Transformation;

$transformation = new Transformation(new Canvas('your robots'));
$transformation->overlay(new Canvas('your frame'))
           ->getCanvas()
           ->show();