PHP - 画像の合成
プリクラやアバター作成を Webアプリで実装する場合、画像の合成が必要になります。真ん中の画像が背景画像となり、それにアイテム(透過のPNG画像)を乗せていきます。背景画像の左上を基準として、アイテムの左上の位置とアイテムの幅と高さを覚えておき PHP の GDライブラリを利用して画像を合成します。
上の画像をクリックすると別画面でプログラムが実行されます。
※ 合成するアイテムを回転させたり、同じアイテムを複数合成できるようにするともう少し便利になるかな。それは jQuery UI で調整できるのでここでは割愛します。
ソースコード
<?php
/*
* 画像の位置やサイズのJSONデータを取得
*/
$aryRes = json_decode(stripslashes($_POST['itemdata']), true);
// 画像数の取得
$iCount = count($aryRes['images']);
/*
* 一番はじめの画像(背景)
*/
$sBackground = $aryRes['images'][0]['src'];
$resBack = imagecreatefrompng($sBackground);
$iBackWidth = imagesx($resBack);
$iBackHeight = imagesy($resBack);
/*
* 表示フレーム
*/
$iFrameWidth = $aryRes['images'][0]['width'];
$iFrameHeight = $aryRes['images'][0]['height'];
$resFrame = imagecreatetruecolor($iFrameWidth,$iFrameHeight);
// 背景画像をリサイズして表示用フレームを作成
imagecopyresampled($resFrame, $resBack, 0, 0, 0, 0,
$iFrameWidth, $iFrameHeight, $iBackWidth, $iBackHeight);
/*
* 背景以外の画像(アイテム)を表示フレームに配置
*/
for ($i = 1; $i < $iCount; ++$i) {
// アイテム画像の取得
$sItem = $aryRes['images'][$i]['src'];
$resItem = imagecreatefrompng($sItem);
$iItemWidth = imagesx($resItem);
$iItemHeight = imagesy($resItem);
// 配置サイズを取得
$iItemNWidth = $aryRes['images'][$i]['width'];
$iItemNHeight = $aryRes['images'][$i]['height'];
// 配置位置を取得
$iItemNTop = $aryRes['images'][$i]['top'];
$iItemNLeft = $aryRes['images'][$i]['left'];
// アイテムの作成
$resItemNew = imagecreatetruecolor($iItemNWidth,$iItemNHeight);
$resNColor = imagecolorallocatealpha($resItemNew, 0, 0, 0, 127);
imagefill($resItemNew, 0, 0, $resNColor);
imagecopyresampled($resItemNew, $resItem, 0, 0, 0, 0,
$iItemNWidth, $iItemNHeight, $iItemWidth, $iItemHeight);
// アイテムの配置
$iExtraTop = (imagesy($resItemNew)-$iItemNHeight)/2;
$iExtraLeft = (imagesx($resItemNew)-$iItemNWidth)/2;
imagecopy($resFrame, $resItemNew,
$iItemNLeft-$iExtraLeft, $iItemNTop-$iExtraTop, 0, 0,
imagesx($resItemNew), imagesy($resItemNew));
}
// 画像の出力
header('Content-type: image/png');
imagepng($resFrame);
imagedestroy($resFrame);
?>
※ このコードは動きの説明のためエラー処理等記述していません。取り扱いには注意してください。