<code
class
=
"language-php"
>
namespace
\clarence\thumbnail;
class
Thumbnail
extends
\Imagick
{
public
static
function
createFromImages(
$images
,
$width
,
$height
){
if
(
empty
(
$images
)){
throw
new
ThumbnailException(
"No images!"
);
}
$thumbnail
=
new
static
();
$thumbnail
->newImage(
$width
,
$height
, 'white', 'jpg');
$thumbnail
->compositeImages(
$images
);
return
$thumbnail
;
}
public
function
compositeImages(
$images
){
$imagesKeys
=
array_keys
(
$images
);
$compositeConfig
=
$this
->calcCompositeImagesPosAndSize(
$images
);
foreach
(
$compositeConfig
as
$index
=>
$cfg
){
$imgKey
=
$imagesKeys
[
$index
];
$img
=
new
\Imagick(
$images
[
$imgKey
]);
$img
=
$this
->makeCompositeThumbnail(
$img
,
$cfg
);
$this
->compositeImage(
$img
, self::COMPOSITE_OVER,
$cfg
['to']['x'],
$cfg
['to']['y']);
}
}
protected
function
makeCompositeThumbnail(\Imagick
$img
,
$cfg
){
$img
->cropThumbnailImage(
$cfg
['size']['width'],
$cfg
['size']['height']);
return
$img
;
}
protected
function
calcCompositeImagesPosAndSize(
$images
){
$width
=
$this
->getImageWidth();
$height
=
$this
->getImageHeight();
switch
(
count
(
$images
)){
case
0:
throw
new
ThumbnailException(
"No images!"
);
case
1:
return
[
0 => [
'to' => [ 'x' => 0, 'y' => 0 ],
'size' => [
'width' =>
$width
,
'height' =>
$height
,
]
]
];
case
2:
return
[
0 => [
'to' => [ 'x' => 0, 'y' => 0 ],
'size' => [
'width' =>
$width
/ 2,
'height' =>
$height
,
]
],
1 => [
'to' => [ 'x' =>
$width
/ 2, 'y' => 0],
'size' => [
'width' =>
$width
/ 2,
'height' =>
$height
,
]
]
];
case
3:
return
[
0 => [
'to' => [ 'x' => 0, 'y' => 0 ],
'size' => [
'width' =>
$width
/ 2,
'height' =>
$height
/ 2,
]
],
1 => [
'to' => [ 'x' =>
$width
/ 2, 'y' => 0],
'size' => [
'width' =>
$width
/ 2,
'height' =>
$height
,
]
],
2 => [
'to' => [ 'x' => 0, 'y' =>
$height
/ 2 ],
'size' => [
'width' =>
$width
/ 2,
'height' =>
$height
/ 2,
]
],
];
default
:
return
[
0 => [
'to' => [ 'x' => 0, 'y' => 0 ],
'size' => [
'width' =>
$width
/ 2,
'height' =>
$height
/ 2,
]
],
1 => [
'to' => [ 'x' =>
$width
/ 2, 'y' => 0],
'size' => [
'width' =>
$width
/ 2,
'height' =>
$height
/ 2,
]
],
2 => [
'to' => [ 'x' => 0, 'y' =>
$height
/ 2 ],
'size' => [
'width' =>
$width
/ 2,
'height' =>
$height
/ 2,
]
],
3 => [
'to' => [ 'x' =>
$width
/ 2, 'y' =>
$height
/ 2],
'size' => [
'width' =>
$width
/ 2,
'height' =>
$height
/ 2,
]
],
];
}
}
}
</code>