[GD]PNG画像合成で背景を白にする

2012/09/28

GDでPNG画像を合成する際、元画像のアルファが影響してにじんでしまうことがある。 特に意図してアルファチャンネルを利用しない場合は、truecolorで合成したほうがいいかも。

(1) imageCreateTrueColor() で画像を作成 (2) imagecolorallocate() でカラー作成 (3) imagefill() で背景塗りつぶし

画像を縦に合成するサンプル

gd_draw_white_image.php

<

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(&#039;image create error!&#039;);
    $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[&#039;image&#039;], $this->image_x, $this->image_y, 0, 0, $values[&#039;width&#039;], $values[&#039;height&#039;]);
    ImageDestroy($values[&#039;image&#039;]);
    $this->image_y+= $values[&#039;height&#039;];
}

/**
 * fetch image
 *
 * @param string $path
 * @return array
 */
function fetchImage($path) {
    $values[&#039;image&#039;] = ImageCreateFromPng($path);
    if ($values[&#039;image&#039;]) {
        $values[&#039;width&#039;] = ImageSX($values[&#039;image&#039;]);
        $values[&#039;height&#039;] = ImageSY($values[&#039;image&#039;]);

        $this->image_widths[] = $values[&#039;width&#039;];
        $this->image_height+= $values[&#039;height&#039;];
    }
    return $values;
}

}