使用PHP将多个PNG图像连接到一个PNG中 [英] Join multiple PNG Images into a single one PNG using PHP

查看:193
本文介绍了使用PHP将多个PNG图像连接到一个PNG中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I´m trying to make custom sprites based on my own PNGs using PHP, but I got two problems:



  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的图书馆一个机会,可以从这里访问:

After one hour trying to do the Job using only PHP GD I decided to give a chance to this Library called "ImageWorkshop" which is accessible from here:


http://phpimageworkshop.com/

结果是真棒,用10行代码来解决问题。
以下是如何:

The result is AWESOME, with less of 10 lines of code I solve the situation. Here is How:

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

(Obviously, first you have to download ImageWorkshop)

注意:我将使用一些描述性代码来确保每个人都理解:)

NOTE: I will use a little bit descriptive code to ensure everybody understanding :)

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库。

By the way this small Library uses the PHP GD library.

这篇关于使用PHP将多个PNG图像连接到一个PNG中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆