简体   繁体   中英

PHP GD, Transparent PNG ontop of Full Color JPG

I am trying to create a custom looking banner avatar for a website. The image below shows what needs to happen:

要显示的图像

As you can see, I have a semi-transparent PNG, a user provided image and I would like to make the third image.

The code that I have written so far is:

$user_id = 1;   
$name_qry = mysql_query("SELECT a.*, b.* FROM mbr_user_name a, mbr_user_information b WHERE a.user_id = '$user_id' AND b.user_id = '$user_id'");
    while($row = mysql_fetch_array($name_qry)){

    $user_name = $row['user_name'];
    $user_email = $row['user_email'];
    $user_avatar = $row['user_avatar'];
    }

    $height = "208";
    $width = "199";
    $top_image = "../images/bannerShadow_cccccb.png";
    $image = imagecreatefrompng("." . $user_avatar);
    $banner = imagecreatefrompng($top_image);

        //Keeping the Banner Trasnparent
        $transBanner = imagecreate($width, $height);
        $color = imagecolorallocatealpha($transBanner, 0, 0, 0, 127);
        imagefill($transBanner, 0, 0, $color);
        imagecopyresampled($transBanner, $banner, 0, 0, 0, 0, $width, $height, $width, $height);


    imagealphablending($transBanner, true);
    imagecopymerge($image, $transBanner, 0, 0, 0, 0, 199, 208, 100);



    imagepng($image);

It outputs something like what is shown below:

形象不佳

I obviously still have to make the user provided image the right size , That is a simple math problem - Right now, I have to make the transparency stay transparent!

If I take out:

imagealphablending($transBanner, true);
imagecopymerge($image, $transBanner, 0, 0, 0, 0, 199, 208, 100);

and change the last line to imagepng($transBanner); , the transparent png will stay transparent!, but once I try to put the two together, It makes the transparency a perfect black color.

Any suggestions?

I did something similar some time ago. There I used a true color image. Just create a new image and copy a resized version of each (avatar and overlay) into it:

<?php
$imgOverlay = imagecreatefrompng('overlay.png');
$imgAvatar = imagecreatefrompng('avatar.png');

$width = imagesx($imgOverlay);
$height = imagesy($imgOverlay);

$imgBanner = imagecreatetruecolor($width, $height);
imagecopyresampled($imgBanner, $imgAvatar, 0, 0, 0, 0, $width, $height, imagesx($imgAvatar), imagesy($imgAvatar));
imagecopyresampled($imgBanner, $imgOverlay, 0, 0, 0, 0, $width, $height, $width, $height);

header('Content-type: image/png');
imagepng($imgBanner);

You may add some calculations to the width/height for a real scale of your avatar when copying $imgAvatar into $imgBanner . The code above will just resize the avatar to fit the overlays size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM