user2451809
user2451809

Reputation: 23

Image create using gd

I am creating image using GD library all the functions are working fine. But the main problem where i stucked that i want to merge png image over an other image but after overlapping it cannot merge properly and looking like jpg or other instead of png. I cannot upload my image here due to low reputation so click on these links below to see the image.

The image which i want to merge is this

Png image

png image

The image where i merge above image is:

merge with

My code is here:

<?php
$im = imagecreate(288,288);
$background_color = imagecolorallocate($im, 230, 248, 248);
$file = 'images/smiley/smile'.$_POST['smiley'].'.png'; 
$bg = imagecreatefrompng($file);
imagealphablending($im, true); 
imagesavealpha($bg, true);
imagecopyresampled($im, $bg, 80, 80, 0, 0, 50, 50, 185, 185);

                           header("Content-Type: image/png");
            $filename = $_SESSION['rand'].'.png';
            imagepng($im,$filename);
            echo '<img src="'.$filename.'" alt="" />';
?>

Upvotes: 0

Views: 517

Answers (1)

Danack
Danack

Reputation: 25701

Your background image doesn't have an alpha channel. This makes the PHP GD library do all of it's copying operations without using an alpha channel, instead just setting each pixel to be fully opaque or transparent, which is not what you want.

The simplest solution to this is to create a new image of the same size as the background that has an alpha channel, and then copy both the background and face into that one.

$baseImage = imagecreatefrompng("../../var/tmp/background.png");
$topImage = imagecreatefrompng("../../var/tmp/face.png");

// Get image dimensions
$baseWidth  = imagesx($baseImage);
$baseHeight = imagesy($baseImage);
$topWidth   = imagesx($topImage);
$topHeight  = imagesy($topImage);

//Create a new image
$imageOut = imagecreatetruecolor($baseWidth, $baseHeight);
//Make the new image definitely have an alpha channel
$backgroundColor = imagecolorallocatealpha($imageOut, 0, 0, 0, 127);
imagefill($imageOut, 0, 0, $backgroundColor);

imagecopy($imageOut, $baseImage, 0, 0, 0, 0, $baseWidth, $baseHeight); //have to play with these
imagecopy($imageOut, $topImage, 0, 0, 0, 0, $topWidth, $topHeight); //have to play with these

//header('Content-Type: image/png');
imagePng($imageOut, "../../var/tmp/output.png");

That code produces this image: enter image description here

Upvotes: 1

Related Questions