How to merge transparent PNG with image using PHP?

Here we can see how to mearge two images with php. In this example one image is jpg. Other one is png. We have to place png image on top of jpg and png image is a transparent one.

For this example I took 200 x 200 px images. Those images are base.jpg and top.png.

apache attack helicopter


Now we have to merge these two images on top of other one with alpha transparency. If we apply following code it will merge the image.

$width = 200;
$height = 200;

$base_image = imagecreatefromjpeg("base.jpg");
$top_image = imagecreatefrompng("top.png");
$merged_image = "merged.png";

imagesavealpha($top_image, true);
imagealphablending($top_image, true);

imagecopy($base_image, $top_image, 0, 0, 0, 0, $width, $height);
imagepng($base_image, $merged_image);

Once we run this code we will get merged png image with the name of merged.png. That image will be look like as follows. Here we have to note one point the function (imagesavealpha, imagealphablending) need to be applied to all png image object.

apache helicopter targeted


In this example we load all images from local directory. But we can use web urls also insted of local images. That time we have to make sure http, https or ftp wrapers are enabled. We can check currently available wrapers on our server using following code.

echo "<pre>";
echo "</pre>";

Out put of the above code will be like follows.

    [0] => php
    [1] => file
    [2] => glob
    [3] => data
    [4] => http
    [5] => ftp
    [6] => zip
    [7] => compress.zlib
    [8] => https
    [9] => ftps
    [10] => compress.bzip2
    [11] => phar
Here we can see all the available wrapers on this perticular server. If we don't have http or https wrapers on this list then we have to enable that on php.ini file. So if we want to enable https simply copy following line to php.ini file and restart the server.



php image
php gd


cache cache cache