Last active
August 1, 2018 08:34
-
-
Save giorrrgio/3904046 to your computer and use it in GitHub Desktop.
best fit images
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"require": { | |
[...] | |
"imagine/Imagine": "dev-master" | |
}, |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme\MyBundle\Service; | |
use Symfony\Component\HttpFoundation\File\File; | |
use Imagine\Image\ImagineInterface; | |
use Imagine\Image\BoxInterface; | |
use Imagine\Image\Point; | |
use Imagine\Image\Box; | |
class ImagineResizer | |
{ | |
protected $imagine; | |
protected $mode; | |
protected $box; | |
public function __construct(ImagineInterface $imagine, BoxInterface $box, $mode = ImageInterface::THUMBNAIL_OUTBOUND) { | |
$this->imagine = $imagine; | |
$this->mode = $mode; | |
$this->box = $box; | |
} | |
public function resize(File $file, $destination) | |
{ | |
$file->move($destination, $file->getClientOriginalName()); | |
$filename = $file->getClientOriginalName(); | |
$image = $this->imagine->open($destination . '/' . $filename); | |
//original size | |
$srcBox = $image->getSize(); | |
//we scale on the smaller dimension | |
if ($srcBox->getWidth() > $srcBox->getHeight()) { | |
$width = $srcBox->getWidth()*($this->box->getHeight()/$srcBox->getHeight()); | |
$height = $this->box->getHeight(); | |
//we center the crop in relation to the width | |
$cropPoint = new Point((max($width - $this->box->getWidth(), 0))/2, 0); | |
} else { | |
$width = $this->box->getWidth(); | |
$height = $srcBox->getHeight()*($this->box->getWidth()/$srcBox->getWidth()); | |
//we center the crop in relation to the height | |
$cropPoint = new Point(0, (max($height - $this->box->getHeight(),0))/2); | |
} | |
$box = new Box($width, $height); | |
//we scale the image to make the smaller dimension fit our resize box | |
$image = $image->thumbnail($box, \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND); | |
//and crop exactly to the box | |
$image->crop($cropPoint, $this->box) | |
->save($destination . '/' . $filename); | |
return $file->getClientOriginalName(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment