PHP GD library used to merge two images

2020-05-09 16:38发布

Okay, so I have two images in a file. One of them is of a t-shirt. The other is of a logo. I used CSS to style the two images so that it looks like the logo is written on the t-shirt. I merely gave the image of a logo a higher z-index in the CSS style sheet. Is there anyway that I could generate an image of both the shirt and the image combined as one using the GD library?

Thanks,

Lance

标签: php gdlib
3条回答
狗以群分
3楼-- · 2020-05-09 17:25

This tutorial should get you started http://www.php.net/manual/en/image.examples.merged-watermark.php and on the right track

查看更多
淡お忘
4楼-- · 2020-05-09 17:26

It's possible. Sample code:

// or whatever format you want to create from
$shirt = imagecreatefrompng("shirt.png"); 

// the logo image
$logo = imagecreatefrompng("logo.png"); 

// You need a transparent color, so it will blend nicely into the shirt.
// In this case, we are selecting the first pixel of the logo image (0,0) and
// using its color to define the transparent color
// If you have a well defined transparent color, like black, you have to
// pass a color created with imagecolorallocate. Example:
// imagecolortransparent($logo, imagecolorallocate($logo, 0, 0, 0));
imagecolortransparent($logo, imagecolorat($logo, 0, 0));

// Copy the logo into the shirt image
$logo_x = imagesx($logo); 
$logo_y = imagesy($logo); 
imagecopymerge($shirt, $logo, 0, 0, 0, 0, $logo_x, $logo_y, 100); 

// $shirt is now the combined image
// $shirt => shirt + logo


//to print the image on browser
header('Content-Type: image/png');
imagepng($shirt);

If you don't want to specify a transparent color, but instead want to use an alpha channel, you have to use imagecopy instead of imagecopymerge. Like this:

// Load the stamp and the photo to apply the watermark to
$logo = imagecreatefrompng("logo.png");
$shirt = imagecreatefrompng("shirt.png");

// Get the height/width of the logo image
$logo_x = imagesx($logo); 
$logo_y = imagesy($logo);

// Copy the logo to our shirt
// If you want to position it more accurately, check the imagecopy documentation
imagecopy($shirt, $logo, 0, 0, 0, 0, $logo_x, $logo_y);

References:
imagecreatefrompng
imagecolortransparent
imagesx
imagesy
imagecopymerge
imagecopy

Tutorial from PHP.net to watermark images
Tutorial from PHP.net to watermark images (using an alpha channel)

查看更多
登录 后发表回答