|
<?php |
|
|
|
namespace App; |
|
|
|
use Gregwar\Image\Image; |
|
use Symfony\Component\HttpFoundation\File\UploadedFile; |
|
|
|
trait ImageTrait |
|
{ |
|
protected $imageWidth, $imageHeight; |
|
|
|
/** |
|
* @param string $size Available sizes: tiny, small, medium, large, huge, original |
|
* |
|
* @return string |
|
*/ |
|
public function imageUrl($size = 'small') |
|
{ |
|
return url($this->generateImage($size)); |
|
} |
|
|
|
/** |
|
* @param string $size Available sizes: tiny, small, medium, large, huge, original |
|
* @param array $options |
|
* |
|
* @return string |
|
*/ |
|
public function image($size = 'small', $options = []) |
|
{ |
|
$attributes = ''; |
|
|
|
foreach ($options as $key => $value) { |
|
$attributes .= "$key=\"$value\" "; |
|
} |
|
|
|
$html = '<img src="%s" %s />'; |
|
|
|
return sprintf($html, |
|
url($this->generateImage($size)), $attributes |
|
); |
|
} |
|
|
|
/** |
|
* @param string|array $size |
|
* |
|
* @return string |
|
*/ |
|
protected function generateImage($size) |
|
{ |
|
$image = $this->openImage(); |
|
|
|
if (is_array($size)) { |
|
$this->imageWidth = $size[0]; |
|
$this->imageHeight = $size[1]; |
|
} |
|
|
|
if ($size == 'tiny') { |
|
$this->imageWidth = $this->imageHeight = 25; |
|
} |
|
|
|
if ($size == 'small') { |
|
$this->imageWidth = $this->imageHeight = 100; |
|
} |
|
|
|
if ($size == 'medium') { |
|
$this->imageWidth = $this->imageHeight = 300; |
|
} |
|
|
|
if ($size == 'large') { |
|
$this->imageWidth = $this->imageHeight = 500; |
|
} |
|
|
|
if ($size == 'huge') { |
|
$this->imageWidth = $this->imageHeight = 800; |
|
} |
|
|
|
$image->zoomCrop($this->imageWidth, $this->imageHeight); |
|
|
|
return $image->jpeg(); |
|
} |
|
|
|
/** |
|
* @return string |
|
*/ |
|
protected function imageDirectory() |
|
{ |
|
if (property_exists($this, 'imageDirectory')) { |
|
return $this->imageDirectory; |
|
} |
|
|
|
return $this->getTable(); |
|
} |
|
|
|
/** |
|
* @return \Gregwar\Image\Image |
|
*/ |
|
protected function openImage() |
|
{ |
|
$directory = $this->imageDirectory(); |
|
|
|
$file = storage_path("images/$directory/{$this->getKey()}.jpg"); |
|
|
|
if (file_exists($file)) { |
|
return Image::open($file); |
|
} |
|
|
|
return Image::open(storage_path('images/no-image.png')); |
|
} |
|
|
|
/** |
|
* @param UploadedFile $file |
|
* |
|
* @return \Symfony\Component\HttpFoundation\File\UploadedFile |
|
* @throws \Exception |
|
*/ |
|
public function saveImage(UploadedFile $file) |
|
{ |
|
$target = storage_path("images/{$this->imageDirectory()}/{$this->getKey()}.jpg"); |
|
|
|
Image::open($file->getPath())->save($target); |
|
|
|
return $file; |
|
} |
|
} |
cool