Merge pull request #3251 from splitbrain/slika

use Slika for image resizing and cropping
This commit is contained in:
Andreas Gohr 2020-11-19 15:46:36 +01:00 committed by GitHub
commit 8b07fee4b3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 2452 additions and 69 deletions

View File

@ -15,7 +15,8 @@
"openpsa/universalfeedcreator": "^1.8",
"aziraphale/email-address-validator": "^2",
"marcusschwarz/lesserphp": "^0.5.1",
"splitbrain/php-cli": "^1.1"
"splitbrain/php-cli": "^1.1",
"splitbrain/slika": "^1.0"
},
"config": {
"platform": {

42
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "dc3e894425a4e285b1c56c2ce4966a60",
"content-hash": "f43d3a0e0afb925e14da17a3b8323a29",
"packages": [
{
"name": "aziraphale/email-address-validator",
@ -516,6 +516,46 @@
"terminal"
],
"time": "2019-12-12T08:24:54+00:00"
},
{
"name": "splitbrain/slika",
"version": "1.0.3",
"source": {
"type": "git",
"url": "https://github.com/splitbrain/slika.git",
"reference": "a357f2ac6a10668c43516ef11220f60da9fab171"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/splitbrain/slika/zipball/a357f2ac6a10668c43516ef11220f60da9fab171",
"reference": "a357f2ac6a10668c43516ef11220f60da9fab171",
"shasum": ""
},
"require-dev": {
"phpunit/phpunit": "^7.0"
},
"suggest": {
"ext-gd": "PHP's builtin image manipulation library. Alternatively use an installation of ImageMagick"
},
"type": "library",
"autoload": {
"psr-4": {
"splitbrain\\slika\\tests\\": "tests",
"splitbrain\\slika\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Andreas Gohr",
"email": "andi@splitbrain.org"
}
],
"description": "Simple image resizing",
"time": "2020-09-01T15:14:41+00:00"
}
],
"packages-dev": [],

View File

@ -2067,40 +2067,37 @@ function media_nstree_li($item){
*/
function media_resize_image($file, $ext, $w, $h=0){
global $conf;
$info = @getimagesize($file); //get original size
if($info == false) return $file; // that's no image - it's a spaceship!
if(!$h) $h = round(($w * $info[1]) / $info[0]);
if(!$w) $w = round(($h * $info[0]) / $info[1]);
if(!$h) $h = $w;
// we wont scale up to infinity
if($w > 2000 || $h > 2000) return $file;
// resize necessary? - (w,h) = native dimensions
if(($w == $info[0]) && ($h == $info[1])) return $file;
//cache
$local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
$mtime = @filemtime($local); // 0 if not exists
$mtime = (int) @filemtime($local); // 0 if not exists
if($mtime > filemtime($file) ||
media_resize_imageIM($ext, $file, $info[0], $info[1], $local, $w, $h) ||
media_resize_imageGD($ext, $file, $info[0], $info[1], $local, $w, $h)
) {
if($conf['fperm']) @chmod($local, $conf['fperm']);
return $local;
$options = [
'quality' => $conf['jpg_quality'],
'imconvert' => $conf['im_convert'],
];
if( $mtime <= (int) @filemtime($file) ) {
try {
\splitbrain\slika\Slika::run($file, $options)
->autorotate()
->resize($w, $h)
->save($local, $ext);
if($conf['fperm']) @chmod($local, $conf['fperm']);
} catch (\splitbrain\slika\Exception $e) {
dbglog($e->getMessage());
return $file;
}
}
//still here? resizing failed
return $file;
return $local;
}
/**
* Crops the given image to the wanted ratio, then calls media_resize_image to scale it
* to the wanted size
*
* Crops are centered horizontally but prefer the upper third of an vertical
* image because most pics are more interesting in that area (rule of thirds)
* Center crops the given image to the wanted size
*
* @author Andreas Gohr <andi@splitbrain.org>
*
@ -2112,55 +2109,33 @@ function media_resize_image($file, $ext, $w, $h=0){
*/
function media_crop_image($file, $ext, $w, $h=0){
global $conf;
if(!$h) $h = $w;
$info = @getimagesize($file); //get original size
if($info == false) return $file; // that's no image - it's a spaceship!
// calculate crop size
$fr = $info[0]/$info[1];
$tr = $w/$h;
// check if the crop can be handled completely by resize,
// i.e. the specified width & height match the aspect ratio of the source image
if ($w == round($h*$fr)) {
return media_resize_image($file, $ext, $w);
}
if($tr >= 1){
if($tr > $fr){
$cw = $info[0];
$ch = (int) ($info[0]/$tr);
}else{
$cw = (int) ($info[1]*$tr);
$ch = $info[1];
}
}else{
if($tr < $fr){
$cw = (int) ($info[1]*$tr);
$ch = $info[1];
}else{
$cw = $info[0];
$ch = (int) ($info[0]/$tr);
}
}
// calculate crop offset
$cx = (int) (($info[0]-$cw)/2);
$cy = (int) (($info[1]-$ch)/3);
// we wont scale up to infinity
if($w > 2000 || $h > 2000) return $file;
//cache
$local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
$mtime = @filemtime($local); // 0 if not exists
$local = getCacheName($file,'.media.'.$w.'x'.$h.'.crop.'.$ext);
$mtime = (int) @filemtime($local); // 0 if not exists
if( $mtime > @filemtime($file) ||
media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
if($conf['fperm']) @chmod($local, $conf['fperm']);
return media_resize_image($local,$ext, $w, $h);
$options = [
'quality' => $conf['jpg_quality'],
'imconvert' => $conf['im_convert'],
];
if( $mtime <= (int) @filemtime($file) ) {
try {
\splitbrain\slika\Slika::run($file, $options)
->autorotate()
->crop($w, $h)
->save($local, $ext);
if($conf['fperm']) @chmod($local, $conf['fperm']);
} catch (\splitbrain\slika\Exception $e) {
dbglog($e->getMessage());
return $file;
}
}
//still here? cropping failed
return media_resize_image($file,$ext, $w, $h);
return $local;
}
/**
@ -2317,9 +2292,11 @@ function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
* @param int $ofs_x offset of crop centre
* @param int $ofs_y offset of crop centre
* @return bool
* @deprecated 2020-09-01
*/
function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
global $conf;
dbg_deprecated('splitbrain\\Slika');
// check if convert is configured
if(!$conf['im_convert']) return false;
@ -2353,9 +2330,11 @@ function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$o
* @param int $ofs_x offset of crop centre
* @param int $ofs_y offset of crop centre
* @return bool
* @deprecated 2020-09-01
*/
function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
global $conf;
dbg_deprecated('splitbrain\\Slika');
if($conf['gdlib'] < 1) return false; //no GDlib available or wanted

View File

@ -6,6 +6,8 @@ $vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'splitbrain\\slika\\tests\\' => array($vendorDir . '/splitbrain/slika/tests'),
'splitbrain\\slika\\' => array($vendorDir . '/splitbrain/slika/src'),
'splitbrain\\phpcli\\' => array($vendorDir . '/splitbrain/php-cli/src'),
'splitbrain\\PHPArchive\\' => array($vendorDir . '/splitbrain/php-archive/src'),
'phpseclib\\' => array($vendorDir . '/phpseclib/phpseclib/phpseclib'),

View File

@ -15,6 +15,8 @@ class ComposerStaticInita19a915ee98347a0c787119619d2ff9b
public static $prefixLengthsPsr4 = array (
's' =>
array (
'splitbrain\\slika\\tests\\' => 23,
'splitbrain\\slika\\' => 17,
'splitbrain\\phpcli\\' => 18,
'splitbrain\\PHPArchive\\' => 22,
),
@ -25,6 +27,14 @@ class ComposerStaticInita19a915ee98347a0c787119619d2ff9b
);
public static $prefixDirsPsr4 = array (
'splitbrain\\slika\\tests\\' =>
array (
0 => __DIR__ . '/..' . '/splitbrain/slika/tests',
),
'splitbrain\\slika\\' =>
array (
0 => __DIR__ . '/..' . '/splitbrain/slika/src',
),
'splitbrain\\phpcli\\' =>
array (
0 => __DIR__ . '/..' . '/splitbrain/php-cli/src',

View File

@ -527,5 +527,47 @@
"optparse",
"terminal"
]
},
{
"name": "splitbrain/slika",
"version": "1.0.3",
"version_normalized": "1.0.3.0",
"source": {
"type": "git",
"url": "https://github.com/splitbrain/slika.git",
"reference": "a357f2ac6a10668c43516ef11220f60da9fab171"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/splitbrain/slika/zipball/a357f2ac6a10668c43516ef11220f60da9fab171",
"reference": "a357f2ac6a10668c43516ef11220f60da9fab171",
"shasum": ""
},
"require-dev": {
"phpunit/phpunit": "^7.0"
},
"suggest": {
"ext-gd": "PHP's builtin image manipulation library. Alternatively use an installation of ImageMagick"
},
"time": "2020-09-01T15:14:41+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"splitbrain\\slika\\tests\\": "tests",
"splitbrain\\slika\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Andreas Gohr",
"email": "andi@splitbrain.org"
}
],
"description": "Simple image resizing"
}
]

View File

@ -0,0 +1,4 @@
*.jpg filter=lfs diff=lfs merge=lfs -text
*.png filter=lfs diff=lfs merge=lfs -text
*.xcf filter=lfs diff=lfs merge=lfs -text
*.bmp filter=lfs diff=lfs merge=lfs -text

2
vendor/splitbrain/slika/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
vendor/
artefacts/

7
vendor/splitbrain/slika/LICENSE vendored Normal file
View File

@ -0,0 +1,7 @@
Copyright 2020 Andreas Gohr <andi@splitbrain.org>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

104
vendor/splitbrain/slika/README.md vendored Normal file
View File

@ -0,0 +1,104 @@
# Slika - simple image handling for PHP
This is a library that covers only the bare basics you need when handling images:
* resizing
* cropping
* rotation
It can use either PHP's libGD or a locally installed ImageMagick binary.
## Installation
Use composer
composer require splitbrain/slika
## Usage
Simply get an Adapter from the Slika factory, run some operations on it and call `save`.
Operations can be chained together. Consider the chain to be one command. Do not reuse the adapter returned by `run()`, it is a single use object. All operations can potentially throw a `\splitbrain\slika\Exception`.
Options (see below) can be passed as a second parameter to the `run` factory.
```php
use \splitbrain\slika\Slika;
use \splitbrain\slika\Exception;
$options = [
'quality' => 75
]
try {
Slika::run('input.png', $options)
->resize(500,500)
->rotate(Slika::ROTATE_CCW
->save('output.jpg', 'jpg');
} catch (Exception $e) {
// conversion went wrong, handle it
}
```
## Operations
### resize
All resize operations will keep the original aspect ratio of the image. There will be no distortion.
Keeping either width or height at zero will auto calculate the value for you.
```php
# fit the image into a bounding box of 500x500 pixels
Slika::run('input.jpg')->resize(500,500)->save('output.png', 'png');
# adjust the image to a maximum width of 500 pixels
Slika::run('input.jpg')->resize(500,0)->save('output.png', 'png');
# adjust the image to a maximum height of 500 pixels
Slika::run('input.jpg')->resize(0,500)->save('output.png', 'png');
```
### crop
Similar to resizing, but this time the image will be cropped to fit the new aspect ratio.
```php
Slika::run('input.jpg')->crop(500,500)->save('output.png', 'png');
```
### rotate
Rotates the image. The parameter passed is one of the EXIF orientation flags:
![orientation flags](https://i.stack.imgur.com/BFqgu.gif)
For your convenience there are three Constants defined:
* `Slika::ROTATE_CCW` counter clockwise rotation
* `Slika::ROTATE_CW` clockwise rotation
* `Slika::ROTATE_TOPDOWN` full 180 degree rotation
```php
Slika::run('input.jpg')->rotate(Slika::ROTATE_CW)->save('output.png', 'png');
```
### autorotate
Rotates the image according to the EXIF rotation tag if found.
```php
Slika::run('input.jpg')->autorotate()->save('output.png', 'png');
```
## Options
Options can be passed as associatiave array as the second parameter in `Slika::run`.
The following options are availble currently:
| Option | Default | Description |
|-------------|--------------------|--------------------------------------------|
| `imconvert` | `/usr/bin/convert` | The path to ImageMagick's `convert` binary |
| `quality` | `92` | The quality when writing JPEG images |

24
vendor/splitbrain/slika/composer.json vendored Normal file
View File

@ -0,0 +1,24 @@
{
"name": "splitbrain/slika",
"description": "Simple image resizing",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Andreas Gohr",
"email": "andi@splitbrain.org"
}
],
"suggest": {
"ext-gd": "PHP's builtin image manipulation library. Alternatively use an installation of ImageMagick"
},
"autoload": {
"psr-4": {
"splitbrain\\slika\\tests\\": "tests",
"splitbrain\\slika\\": "src"
}
},
"require-dev": {
"phpunit/phpunit": "^7.0"
}
}

1498
vendor/splitbrain/slika/composer.lock generated vendored Normal file

File diff suppressed because it is too large Load Diff

87
vendor/splitbrain/slika/src/Adapter.php vendored Normal file
View File

@ -0,0 +1,87 @@
<?php
namespace splitbrain\slika;
abstract class Adapter
{
/** @var string path tot he image */
protected $imagepath;
/** @var array Adapter Options */
protected $options;
/**
* New Slika Adapter
*
* @param string $imagepath path to the original image
* @param array $options set options
* @throws Exception
*/
public function __construct($imagepath, $options = [])
{
if (!file_exists($imagepath)) {
throw new Exception('image file does not exist');
}
if (!is_readable($imagepath)) {
throw new Exception('image file is not readable');
}
$this->imagepath = $imagepath;
$this->options = array_merge(Slika::DEFAULT_OPTIONS, $options);
}
/**
* Rote the image based on the rotation exif tag
*
* @return Adapter
*/
abstract public function autorotate();
/**
* Rotate and/or flip the image
*
* This expects an orientation flag as stored in EXIF data. For typical operations,
* Slika::ROTATE_* constants are defined.
*
* @param int $orientation Exif rotation flags
* @return Adapter
* @see https://stackoverflow.com/a/53697440 for info on the rotation constants
*/
abstract public function rotate($orientation);
/**
* Resize to make image fit the given dimension (maintaining the aspect ratio)
*
* You may omit one of the dimensions to auto calculate it based on the aspect ratio
*
* @param int $width
* @param int $height
* @return Adapter
*/
abstract public function resize($width, $height);
/**
* Resize to the given dimension, cropping the image as needed
*
* You may omit one of the dimensions to use a square area
*
* @param int $width
* @param int $height
* @return Adapter
*/
abstract public function crop($width, $height);
/**
* Save the new file
*
* @param string $path
* @param string $extension The type of image to save, empty for original
* @return void
*/
abstract public function save($path, $extension = '');
}

View File

@ -0,0 +1,10 @@
<?php
namespace splitbrain\slika;
class Exception extends \Exception
{
}

View File

@ -0,0 +1,396 @@
<?php /** @noinspection PhpComposerExtensionStubsInspection */
namespace splitbrain\slika;
class GdAdapter extends Adapter
{
/** @var resource libGD image */
protected $image;
/** @var int width of the current image */
protected $width = 0;
/** @var int height of the current image */
protected $height = 0;
/** @var string the extension of the file we're working with */
protected $extension;
/** @inheritDoc */
public function __construct($imagepath, $options = [])
{
parent::__construct($imagepath, $options);
$this->image = $this->loadImage($imagepath);
}
/**
* Clean up
*/
public function __destruct()
{
if (is_resource($this->image)) {
imagedestroy($this->image);
}
}
/** @inheritDoc
* @throws Exception
* @link https://gist.github.com/EionRobb/8e0c76178522bc963c75caa6a77d3d37#file-imagecreatefromstring_autorotate-php-L15
*/
public function autorotate()
{
if ($this->extension !== 'jpeg') {
return $this;
}
$orientation = 1;
if (function_exists('exif_read_data')) {
// use PHP's exif capablities
$exif = exif_read_data($this->imagepath);
if (!empty($exif['Orientation'])) {
$orientation = $exif['Orientation'];
}
} else {
// grep the exif info from the raw contents
// we read only the first 70k bytes
$data = file_get_contents($this->imagepath, false, null, 0, 70000);
if (preg_match('@\x12\x01\x03\x00\x01\x00\x00\x00(.)\x00\x00\x00@', $data, $matches)) {
// Little endian EXIF
$orientation = ord($matches[1]);
} else if (preg_match('@\x01\x12\x00\x03\x00\x00\x00\x01\x00(.)\x00\x00@', $data, $matches)) {
// Big endian EXIF
$orientation = ord($matches[1]);
}
}
return $this->rotate($orientation);
}
/**
* @inheritDoc
* @throws Exception
*/
public function rotate($orientation)
{
$orientation = (int)$orientation;
if ($orientation < 0 || $orientation > 8) {
throw new Exception('Unknown rotation given');
}
if ($orientation <= 1) {
// no rotation wanted
return $this;
}
// fill color
$transparency = imagecolorallocatealpha($this->image, 0, 0, 0, 127);
// rotate
if (in_array($orientation, [3, 4])) {
$image = imagerotate($this->image, 180, $transparency, 1);
}
if (in_array($orientation, [5, 6])) {
$image = imagerotate($this->image, -90, $transparency, 1);
list($this->width, $this->height) = [$this->height, $this->width];
} elseif (in_array($orientation, [7, 8])) {
$image = imagerotate($this->image, 90, $transparency, 1);
list($this->width, $this->height) = [$this->height, $this->width];
}
/** @var resource $image is now defined */
// additionally flip
if (in_array($orientation, [2, 5, 7, 4])) {
imageflip($image, IMG_FLIP_HORIZONTAL);
}
imagedestroy($this->image);
$this->image = $image;
//keep png alpha channel if possible
if ($this->extension == 'png' && function_exists('imagesavealpha')) {
imagealphablending($this->image, false);
imagesavealpha($this->image, true);
}
return $this;
}
/**
* @inheritDoc
* @throws Exception
*/
public function resize($width, $height)
{
list($width, $height) = $this->boundingBox($width, $height);
$this->resizeOperation($width, $height);
return $this;
}
/**
* @inheritDoc
* @throws Exception
*/
public function crop($width, $height)
{
list($this->width, $this->height, $offsetX, $offsetY) = $this->cropPosition($width, $height);
$this->resizeOperation($width, $height, $offsetX, $offsetY);
return $this;
}
/**
* @inheritDoc
* @throws Exception
*/
public function save($path, $extension = '')
{
if ($extension === 'jpg') {
$extension = 'jpeg';
}
if ($extension === '') {
$extension = $this->extension;
}
$saver = 'image' . $extension;
if (!function_exists($saver)) {
throw new Exception('Can not save image format ' . $extension);
}
if ($extension == 'jpeg') {
imagejpeg($this->image, $path, $this->options['quality']);
} else {
$saver($this->image, $path);
}
imagedestroy($this->image);
}
/**
* Initialize libGD on the given image
*
* @param string $path
* @return resource
* @throws Exception
*/
protected function loadImage($path)
{
// Figure out the file info
$info = getimagesize($path);
if ($info === false) {
throw new Exception('Failed to read image information');
}
$this->width = $info[0];
$this->height = $info[1];
// what type of image is it?
$this->extension = image_type_to_extension($info[2], false);
$creator = 'imagecreatefrom' . $this->extension;
if (!function_exists($creator)) {
throw new Exception('Can not work with image format ' . $this->extension);
}
// create the GD instance
$image = @$creator($path);
if ($image === false) {
throw new Exception('Failed to load image wiht libGD');
}
return $image;
}
/**
* Creates a new blank image to which we can copy
*
* Tries to set up alpha/transparency stuff correctly
*
* @param int $width
* @param int $height
* @return resource
* @throws Exception
*/
protected function createImage($width, $height)
{
// create a canvas to copy to, use truecolor if possible (except for gif)
$canvas = false;
if (function_exists('imagecreatetruecolor') && $this->extension != 'gif') {
$canvas = @imagecreatetruecolor($width, $height);
}
if (!$canvas) {
$canvas = @imagecreate($width, $height);
}
if (!$canvas) {
throw new Exception('Failed to create new canvas');
}
//keep png alpha channel if possible
if ($this->extension == 'png' && function_exists('imagesavealpha')) {
imagealphablending($canvas, false);
imagesavealpha($canvas, true);
}
//keep gif transparent color if possible
if ($this->extension == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
if (function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
$transcolorindex = @imagecolortransparent($this->image);
if ($transcolorindex >= 0) { //transparent color exists
$transcolor = @imagecolorsforindex($this->image, $transcolorindex);
$transcolorindex = @imagecolorallocate(
$canvas,
$transcolor['red'],
$transcolor['green'],
$transcolor['blue']
);
@imagefill($canvas, 0, 0, $transcolorindex);
@imagecolortransparent($canvas, $transcolorindex);
} else { //filling with white
$whitecolorindex = @imagecolorallocate($canvas, 255, 255, 255);
@imagefill($canvas, 0, 0, $whitecolorindex);
}
} else { //filling with white
$whitecolorindex = @imagecolorallocate($canvas, 255, 255, 255);
@imagefill($canvas, 0, 0, $whitecolorindex);
}
}
return $canvas;
}
/**
* Calculate new size
*
* If widht and height are given, the new size will be fit within this bounding box.
* If only one value is given the other is adjusted to match according to the aspect ratio
*
* @param int $width width of the bounding box
* @param int $height height of the bounding box
* @return array (width, height)
* @throws Exception
*/
protected function boundingBox($width, $height)
{
if ($width == 0 && $height == 0) {
throw new Exception('You can not resize to 0x0');
}
if (!$height) {
// adjust to match width
$height = round(($width * $this->height) / $this->width);
} else if (!$width) {
// adjust to match height
$width = round(($height * $this->width) / $this->height);
} else {
// fit into bounding box
$scale = min($width / $this->width, $height / $this->height);
$width = $this->width * $scale;
$height = $this->height * $scale;
}
return [$width, $height];
}
/**
* Calculates crop position
*
* Given the wanted final size, this calculates which exact area needs to be cut
* from the original image to be then resized to the wanted dimensions.
*
* @param int $width
* @param int $height
* @return array (cropWidth, cropHeight, offsetX, offsetY)
* @throws Exception
*/
protected function cropPosition($width, $height)
{
if ($width == 0 && $height == 0) {
throw new Exception('You can not crop to 0x0');
}
if (!$height) {
$height = $width;
}
if (!$width) {
$width = $height;
}
// calculate ratios
$oldRatio = $this->width / $this->height;
$newRatio = $width / $height;
// calulate new size
if ($newRatio >= 1) {
if ($newRatio > $oldRatio) {
$cropWidth = $this->width;
$cropHeight = (int)($this->width / $newRatio);
} else {
$cropWidth = (int)($this->height * $newRatio);
$cropHeight = $this->height;
}
} else {
if ($newRatio < $oldRatio) {
$cropWidth = (int)($this->height * $newRatio);
$cropHeight = $this->height;
} else {
$cropWidth = $this->width;
$cropHeight = (int)($this->width / $newRatio);
}
}
// calculate crop offset
$offsetX = (int)(($this->width - $cropWidth) / 2);
$offsetY = (int)(($this->height - $cropHeight) / 2);
return [$cropWidth, $cropHeight, $offsetX, $offsetY];
}
/**
* resize or crop images using PHP's libGD support
*
* @param int $toWidth desired width
* @param int $toHeight desired height
* @param int $offsetX offset of crop centre
* @param int $offsetY offset of crop centre
* @throws Exception
*/
protected function resizeOperation($toWidth, $toHeight, $offsetX = 0, $offsetY = 0)
{
$newimg = $this->createImage($toWidth, $toHeight);
//try resampling first, fall back to resizing
if (
!function_exists('imagecopyresampled') ||
!@imagecopyresampled(
$newimg,
$this->image,
0,
0,
$offsetX,
$offsetY,
$toWidth,
$toHeight,
$this->width,
$this->height
)
) {
imagecopyresized(
$newimg,
$this->image,
0,
0,
$offsetX,
$offsetY,
$toWidth,
$toHeight,
$this->width,
$this->height
);
}
// destroy original GD image ressource and replace with new one
imagedestroy($this->image);
$this->image = $newimg;
$this->width = $toWidth;
$this->height = $toHeight;
}
}

View File

@ -0,0 +1,124 @@
<?php
namespace splitbrain\slika;
class ImageMagickAdapter extends Adapter
{
/** @var array the CLI arguments to run imagemagick */
protected $args = [];
/** @inheritDoc */
public function __construct($imagepath, $options = [])
{
parent::__construct($imagepath, $options);
if (!is_executable($this->options['imconvert'])) {
throw new Exception('Can not find or run ' . $this->options['imconvert']);
}
$this->args[] = $this->options['imconvert'];
$this->args[] = $imagepath;
}
/** @inheritDoc */
public function autorotate()
{
$this->args[] = '-auto-orient';
return $this;
}
/** @inheritDoc */
public function rotate($orientation)
{
$orientation = (int)$orientation;
if ($orientation < 0 || $orientation > 8) {
throw new Exception('Unknown rotation given');
}
// rotate
$this->args[] = '-rotate';
if (in_array($orientation, [3, 4])) {
$this->args[] = '180';
} elseif (in_array($orientation, [5, 6])) {
$this->args[] = '90';
} elseif (in_array($orientation, [7, 8])) {
$this->args[] = '270';
}
// additionally flip
if (in_array($orientation, [2, 5, 7, 4])) {
$this->args[] = '-flop';
}
return $this;
}
/**
* @inheritDoc
* @throws Exception
*/
public function resize($width, $height)
{
if ($width == 0 && $height == 0) {
throw new Exception('You can not resize to 0x0');
}
if ($width == 0) $width = '';
if ($height == 0) $height = '';
$size = $width . 'x' . $height;
$this->args[] = '-resize';
$this->args[] = $size;
return $this;
}
/**
* @inheritDoc
* @throws Exception
*/
public function crop($width, $height)
{
if ($width == 0 && $height == 0) {
throw new Exception('You can not crop to 0x0');
}
if ($width == 0) $width = $height;
if ($height == 0) $height = $width;
$this->args[] = '-gravity';
$this->args[] = 'center';
$this->args[] = '-crop';
$this->args[] = $width . 'x' . $height . '+0+0';
$this->args[] = '+repage';
return $this;
}
/**
* @inheritDoc
* @throws Exception
*/
public function save($path, $extension = '')
{
if ($extension === 'jpg') {
$extension = 'jpeg';
}
$this->args[] = '-quality';
$this->args[] = $this->options['quality'];
if ($extension !== '') $path = $extension . ':' . $path;
$this->args[] = $path;
$args = array_map('escapeshellarg', $this->args);
$cmd = join(' ', $args);
$output = [];
$return = 0;
exec($cmd, $output, $return);
if ($return !== 0) {
throw new Exception('ImageMagick returned non-zero exit code for ' . $cmd);
}
}
}

53
vendor/splitbrain/slika/src/Slika.php vendored Normal file
View File

@ -0,0 +1,53 @@
<?php
namespace splitbrain\slika;
class Slika
{
/** @var int rotate an image counter clock wise */
const ROTATE_CCW = 8;
/** @var int rotate an image clock wise */
const ROTATE_CW = 6;
/** @var int rotate on it's head */
const ROTATE_TOPDOWN = 3;
const DEFAULT_OPTIONS = [
'quality' => 92,
'imconvert' => '/usr/bin/convert',
];
/**
* This is a factory only, thus the constructor is private
*/
private function __construct()
{
// there is no constructor.
}
/**
* Start processing the image
*
* @param string $imagePath
* @param array $options
* @return Adapter
* @throws Exception
*/
public static function run($imagePath, $options = [])
{
$options = array_merge(self::DEFAULT_OPTIONS, $options);
if (is_executable($options['imconvert'])) {
return new ImageMagickAdapter($imagePath, $options);
}
if (function_exists('gd_info')) {
return new GdAdapter($imagePath, $options);
}
throw new Exception('No suitable Adapter found');
}
}