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