PHP | Imagickで画像を重ねて合成する方法

PHPのImagickを利用して2枚の画像を重ねて(合成して)ファイルを保存する方法を紹介しています。
compositeImage()とgetImageCompose()について
Imagickを使った画像の合成にはcompositeImage()が利用可能です。
元画像->compositeImage(合成する画像, 合成演算子, 始点X, 始点Y);
サンプルでは$img1と$img2を用意して以下のように記述しています。
$img1->compositeImage($img2, $img2->getImageCompose(), 0, 0);
getImageCompose()にて$img2の合成演算子を取得しています。
$img2->getImageCompose()
Imagickで同じサイズの画像を重ねる
重ねる2つの画像が縦横幅が同じサイズであれは、compositeImage()で始点を0,0にして実行すれば問題なく重なった画像が作成可能です。
$img1 = new Imagick('img1.png');
$img2 = new Imagick('img2.png');
$img2->setBackgroundColor(new ImagickPixel('transparent')); //透過処理を有効にする
$img1->compositeImage($img2, $img2->getImageCompose(), 0, 0); //画像を重ねる
$img1->writeImage('new-image.png'); //画像をファイルに保存
$img1->clear();
$img1->destroy();
$img2->clear();
$img2->destroy();
背面にくる画像


前面にくる画像


上記PHPコードで合成された画像


※サイト軽量化の都合上、PNGファイルはWebPファイルに変換されています
Imagickで違うサイズの画像を重ねる
$img1 = new Imagick('img1.png');
$img1->thumbnailImage(1000, 500); //作成する画像のサイズを指定
$img2 = new Imagick('img2.png');
$img2->setBackgroundColor(new ImagickPixel('transparent')); //透過処理を有効にする
$img2->thumbnailImage(0, 500); //画像1と高さを合わせてリサイズ
$img1->compositeImage($img2, $img2->getImageCompose(), 250, 0); //画像を重ねる
$img1->writeImage('new-image.png'); //画像をファイルに保存
$img1->clear();
$img1->destroy();
$img2->clear();
$img2->destroy();
高さは同じにしていますので、X軸の開始位置だけ中央に調節しています。
サンプルでは$img1の中央になる500pxから、$img2を半分だけ左にずらすのに250pxを引いて250pxとしています。


前面にくる画像


上記PHPコードで合成された画像


※サイト軽量化の都合上、PNGファイルはWebPファイルに変換されています
ディスカッション
コメント一覧
まだ、コメントがありません