forked from CostaRico/yii2-images
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Imagine.php
65 lines (48 loc) · 2.03 KB
/
Imagine.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
namespace bstuff\yii2images;
use yii;
use Imagine\Image\Box;
use Imagine\Image\ManipulatorInterface;
use Imagine\Image\Color;
use Imagine\Image\Point;
class Imagine extends \yii\imagine\Image
{
public static function fitted($filename, $width, $height, $fit=false) {
$img = static::getImagine()->open(Yii::getAlias($filename));
if (!($width || $height)) {
return $img;
}
$sourceBox = $img->getSize();
if ($width && !$height) {
$k = $width / $sourceBox->getWidth();
if ($fit) {
$img = $img->resize(new Box(ceil($k*$sourceBox->getWidth()), ceil($k*$sourceBox->getHeight())));
} elseif ($k < 1) {
$img = $img->resize(new Box($k*$sourceBox->getWidth(), $k*$sourceBox->getHeight()));
}
return $img;
}
if (!$width && $height) {
$k = $height / $sourceBox->getHeight();
if ($fit) {
$img = $img->resize(new Box(ceil($k*$sourceBox->getWidth()), ceil($k*$sourceBox->getHeight())));
} elseif ($k < 1) {
$img = $img->resize(new Box($k*$sourceBox->getWidth(), $k*$sourceBox->getHeight()));
}
return $img;
}
$kx = $width / $sourceBox->getWidth();
$ky = $height / $sourceBox->getHeight();
if ($fit) {
$k = min([$kx, $ky]);
return $img->resize(new Box($k*$sourceBox->getWidth(), $k*$sourceBox->getHeight()));
} else {
$k = max([$kx, $ky]);
$startX = ($width < $k*$sourceBox->getWidth()) ? ceil(.5*($k*$sourceBox->getWidth() - $width)) : 0;
$startY = ($height < $k*$sourceBox->getHeight()) ? ceil(.5*($k*$sourceBox->getHeight() - $height)) : 0;
$img = $img->resize(new Box($k*$sourceBox->getWidth(), $k*$sourceBox->getHeight()))
->crop(new Point($startX,$startY), new Box($width, $height));
}
return $img;
}
}