Sanjana Nair
Sanjana Nair

Reputation: 2785

Merge an image with background image gives black background in php

I have a light blue image set as $dest. I have the logo set as logo1

I want to insert the logo into the light blue image. So I tried the following:

<?php 
            $dest = imagecreatefrompng('template.png');
            $logo1 = 'tst.png';

            $logo1created = imagecreatefrompng($logo1);

            imagealphablending($logo1created,true);
            imagesavealpha($logo1created, true);
            
            $logo1width = imagesx($logo1created);
            $logo1height = imagesy($logo1created);

            $bg_color = imagecolorat($logo1created,1,1);  //get color of top-left pixel
            imagecolortransparent($logo1created, $bg_color);

            imagecopymerge($dest, $logo1created, 70, 132, 0, 0, $logo1width, $logo1height, 100);
            header('Content-Type: image/png');
            imagepng($dest);
            imagedestroy($dest);
            imagedestroy($logo1created);
    ?>

I get the following as the output.

enter image description here

The logo is not transparent (it has a white background) and I have resized the image to 124*30

enter image description here

I want to set transparent background to the logo when I do that there is a black background as per the screenshot above. I am not sure why? Also, the image is blurred. Can someone help me fix this?

Thanks!

Upvotes: 0

Views: 354

Answers (1)

Ken Lee
Ken Lee

Reputation: 8043

Please try the following: (you may adjust the x and y by changing the values 60,70 to other values)

<?php 


function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){ 
        // creating a cut resource 
        $cut = imagecreatetruecolor($src_w, $src_h); 

        // copying relevant section from background to the cut resource 
        imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h); 

        // copying relevant section from watermark to the cut resource 
        imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h); 

        // insert cut resource to destination image 
        imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct); 
    } 



$base = imagecreatefrompng('template.png');
$logo1 = 'tst.png';
$logo = imagecreatefrompng($logo1);
imagecopymerge_alpha($base, $logo, 60, 70, 0, 0, 124, 30, 100);
header('Content-Type: image/png');
imagepng($base);


    ?>

Upvotes: 1

Related Questions