GDでPNG画像を合成する際、元画像のアルファが影響してにじんでしまうことがある。 特に意図してアルファチャンネルを利用しない場合は、truecolorで合成したほうがいいかも。
(1) imageCreateTrueColor() で画像を作成 (2) imagecolorallocate() でカラー作成 (3) imagefill() で背景塗りつぶし
<
pre class="language-php"><?php
$paths[] = './images/sample_hource.png';
$paths[] = './images/sample_sheep.png';
$paths[] = './images/sample_dog.png';
$gd_image = new GDImage(); $gd_image->drawImage($paths);
class GDImage { public $image_widths = []; public $image_width = 0; public $image_height = 0; public $r_color = 255; public $g_color = 255; public $b_color = 255;
/**
* draw image
*
* @param array $paths
* @return void
*/
function drawImage($paths) {
if (!$paths) return;
foreach ($paths as $path) {
$images[] = $this->fetchImage($path);
}
$this->image_width = max($this->image_widths);
$this->createImage();
foreach ($images as $image) {
$this->addImage($image);
}
$this->drawPng();
}
/**
* create image
*
* @return void
*/
function createImage() {
$this->image_x = 0;
$this->image_y = 0;
$this->marge_image = imageCreateTrueColor($this->image_width, $this->image_height);
if (!$this->marge_image) exit('image create error!');
$white = imagecolorallocate($this->marge_image, $this->r_color, $this->g_color, $this->b_color);
imagefill($this->marge_image, 0, 0, $white);
}
/**
* draw png
*
* @return void
*/
function drawPng() {
header("Content-type: image/png");
ImagePng($this->marge_image);
ImageDestroy($this->marge_image);
exit;
}
/**
* add image
*
* @param array $values
* @return void
*/
function addImage($values) {
ImageCopy($this->marge_image, $values['image'], $this->image_x, $this->image_y, 0, 0, $values['width'], $values['height']);
ImageDestroy($values['image']);
$this->image_y+= $values['height'];
}
/**
* fetch image
*
* @param string $path
* @return array
*/
function fetchImage($path) {
$values['image'] = ImageCreateFromPng($path);
if ($values['image']) {
$values['width'] = ImageSX($values['image']);
$values['height'] = ImageSY($values['image']);
$this->image_widths[] = $values['width'];
$this->image_height+= $values['height'];
}
return $values;
}
}