使用PHP将多个PNG图像连接到一个PNG中


Join multiple PNG Images into a single one PNG using PHP

我正试图使用PHP基于自己的PNG制作自定义精灵,但我遇到了两个问题:

  1. 输出图像它是一组堆叠的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'); 

在尝试仅使用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库。