开发者

PHP GD library used to merge two images

开发者 https://www.devze.com 2023-03-14 16:18 出处:网络
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.

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


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)


Yes.

http://php.net/manual/en/book.image.php


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

0

精彩评论

暂无评论...
验证码 换一张
取 消