在PHP中進行圖像合成,可以使用GD庫或Imagick擴展。以下是使用這兩種方法的簡單示例:
<?php
header('Content-Type: image/png');
// 創建圖像資源
$image1 = imagecreatefrompng('image1.png');
$image2 = imagecreatefrompng('image2.png');
// 獲取圖像尺寸
$width1 = imagesx($image1);
$height1 = imagesy($image1);
$width2 = imagesx($image2);
$height2 = imagesy($image2);
// 創建一個空白畫布,用于放置合成圖像
$canvas_width = max($width1, $width2);
$canvas_height = max($height1, $height2);
$canvas = imagecreatetruecolor($canvas_width, $canvas_height);
// 將圖像1復制到畫布上
imagefilledrectangle($canvas, 0, 0, $width1, $height1, imagecolorallocate($canvas, 255, 255, 255));
imagecopy($canvas, $image1, 0, 0, 0, 0, $width1, $height1);
// 將圖像2復制到畫布上
imagefilledrectangle($canvas, 0, 0, $width2, $height2, imagecolorallocate($canvas, 255, 255, 255));
imagecopy($canvas, $image2, 0, 0, 0, 0, $width2, $height2);
// 輸出合成圖像
imagepng($canvas);
imagedestroy($canvas);
imagedestroy($image1);
imagedestroy($image2);
?>
首先,確保已經安裝了Imagick擴展。在命令行中運行以下命令來安裝:
sudo apt-get install php-imagick
然后,創建一個PHP文件,如image_composition.php
,并添加以下代碼:
<?php
header('Content-Type: image/png');
// 創建Imagick對象
$image1 = new Imagick('image1.png');
$image2 = new Imagick('image2.png');
// 獲取圖像尺寸
$width1 = $image1->getWidth();
$height1 = $image1->getHeight();
$width2 = $image2->getWidth();
$height2 = $image2->getHeight();
// 創建一個空白畫布,用于放置合成圖像
$canvas_width = max($width1, $width2);
$canvas_height = max($height1, $height2);
$canvas = new Imagick();
$canvas->setSize($canvas_width, $canvas_height);
$canvas->setFormat('png');
$canvas->setColorSpace(Imagick::COLORSPACE_RGB);
$canvas->setImageBackgroundColor(new ImagickPixel('white'));
// 將圖像1復制到畫布上
$image1->resizeImage($canvas_width, $canvas_height, Imagick::FILTER_LANCZOS, 1);
$image1->setImageOffset(new ImagickPixel('none'), 0);
$canvas->addImage($image1);
// 將圖像2復制到畫布上
$image2->resizeImage($canvas_width, $canvas_height, Imagick::FILTER_LANCZOS, 1);
$image2->setImageOffset(new ImagickPixel('none'), 0);
$canvas->addImage($image2);
// 輸出合成圖像
echo $canvas->getImagesBlob();
?>
這兩個示例都展示了如何將兩個圖像合成到一個畫布上。你可以根據需要調整圖像的位置、大小和透明度等參數。