I have an array of valid image sources and I want to merge them horizontally using ImageMagick in PHP.
Code:
JavaScript
x
$imagePartsData = ["<VALID JPG DATA 1>", "<VALID JPG DATA 2>", ];
$initImage = function($source): Imagick
{
$im = new Imagick();
$im->setFormat('png');
$im->readImageBlob($source);
return $im;
};
$firstPart = $initImage($imagePartsData[0]);
// foreach other parts
for($i = 1, $c = count($imagePartsData); $i < $c; $i++)
{
$part = $initImage($imagePartsData[$i]);
$firstPart->addImage($part);
}
$firstPart->resetIterator();
$combined = $firstPart->appendImages(false);
$combined->setImageFormat("png");
header('Content-Type: image/png');
echo $combined;
The result is black background with white square
Expected result: 4 .png images merged into 1 presenting people.
Advertisement
Answer
My solution:
$imagePartsData
is an array of image sources sorted from left to right so in for loop it adds images properly.
JavaScript
function saveImage(Imagick $imagick)
{
$imagick->setImageFormat("png");
$imagick->writeImageFile(fopen('result.png', 'wb'));
die('saved');
}
function initImage(string $source): Imagick
{
$im = new Imagick();
$im->setFormat('png');
$im->readImageBlob($source);
return $im;
}
$firstPart = initImage($imagePartsData[0]);
$partWidth = $firstPart->getImageWidth();
$partHeight = $firstPart->getImageHeight();
// foreach other parts
for($i = 1, $c = count($imagePartsData); $i < $c; $i++)
{
$part = initImage($imagePartsData[$i]);
$firstPart->addImage($part);
}
$montage = $firstPart->montageImage(new ImagickDraw(), $c.'x1', $partWidth.'x'.$partHeight, 0, '0');
saveImage($montage);
The result is expected! The picture (result.png) of people merged from 4 equal size images.