2014-04-15 47 views
1

我正尝试基于使用PHP我自己的PNG图像进行自定义精灵,但我有两个问题:加入多个PNG图像到一个单一的一个PNG使用PHP

  1. 输出图像it'sa集合堆叠的PNG ...换句话说:源PNG是一个优于其他的。
  2. 我需要输出图像的透明背景!

这是我使用的代码:

$width = 210; 
$height = 190; 

$layers = array(); 
$layers[] = imagecreatefrompng("copy.png"); 
$layers[] = imagecreatefrompng("cut.png"); 

$image = imagecreatetruecolor($width, $height); 

// to make background transparent? 
imagealphablending($image, false); 
$transparency = imagecolorallocatealpha($image, 0, 0, 0, 127); 
imagefill($image, 0, 0, $transparency); 
imagesavealpha($image, true); 

imagealphablending($image, true); 
for ($i = 0; $i < count($layers); $i++) { 
    imagecopy($image, $layers[$i], 0, 0, 0, 0, $width, $height); 
} 
imagealphablending($image, false); 
imagesavealpha($image, true); 

imagepng($image, 'final_img.png'); 

回答

2

一个小时后试图只用PHP GD我决定给一个机会,这个库称为“ImageWorkshop”这是应该做的工作访问从这里开始:

http://phpimageworkshop.com/

结果非常好,我用少于10行的代码解决了这种情况。 这里是如何:

(当然,首先你必须下载ImageWorkshop)

注:我会有点用描述性的代码,以确保每个人都理解:)

require_once('libs/PHPImageWorkshop/ImageWorkshop.php'); 

/*The Empty Layer have 100x100... And is TRANSPARENT!!*/ 
$emptyLayer = ImageWorkshop::initVirginLayer(100, 100); 

$cut = ImageWorkshop::initFromPath(__DIR__ . '/icons/copy.png'); 
$copy = ImageWorkshop::initFromPath(__DIR__ . '/icons/cut.png'); 

/*Set the position of "cut" and "copy" icons inside the emptyLayer*/ 
$emptyLayer->addLayerOnTop($cut, 20, 10, 'LT'); 
$emptyLayer->addLayerOnTop($copy, 20, 30, 'LT'); 

// Saving the result 
$dirPath = __DIR__ . "/icons/"; 
$filename = "output.png"; 
$createFolders = true; //will create the folder if not exist 
$backgroundColor = null; // transparent, only for PNG (otherwise it will be white if set null) 
$imageQuality = 100; // useless for GIF, usefull for PNG and JPEG (0 to 100%) 

$emptyLayer->save($dirPath, $filename, $createFolders, $backgroundColor, $imageQuality); 

这就是所有!

顺便说一句,这个小型图书馆使用PHP GD库。