kuvia/app/Helper/ImagePreparation.php

82 lines
2.9 KiB
PHP

<?php
namespace App\Helper;
use App\Entity\File;
use App\Log;
use Intervention\Image\ImageManager;
class ImagePreparation {
public function prepare(File $file, ?int $size, ?File $watermarkFile) :string {
$img = $this->prepareImage($file, $size, $watermarkFile);
$jpg = (string)$img->encode('jpg', 100);
$img->destroy();
return $jpg;
}
public function prepareImage(File $file, ?int $size, ?File $watermarkFile) : \Intervention\Image\Image {
$manager = new ImageManager(array('driver' => 'imagick'));
$img = $manager->make($file->getContent());
$watermark = null;
if(!is_null($watermarkFile)) {
$watermark = $manager->make($watermarkFile->getContent());
}
if(!is_null($size)) {
$img = $this->resizeImage($img, $size);
}
if(!is_null($watermark)) {
$img = $this->addWatermarkImage($img, $watermark);
}
return $img;
}
private function resizeImage(\Intervention\Image\Image $img, int $size) : \Intervention\Image\Image
{
if($img->getWidth() > $img->getHeight()) {
$newWidth = $size;
$newHeight = $img->getHeight() * ($newWidth / $img->getWidth() );
} else {
$newHeight = $size;
$newWidth = $img->getWidth() * ($newHeight / $img->getHeight());
}
if($newHeight >= $img->getHeight() || $newWidth >= $img->getWidth()) {
\Illuminate\Support\Facades\Log::debug("No resize because orginal is smaller");
} else {
$img->resize($newWidth, $newHeight);
}
return $img;
}
private function addWatermarkImage(\Intervention\Image\Image $img, \Intervention\Image\Image $watermark) : \Intervention\Image\Image {
if($watermark->getWidth() > $img->getWidth()) {
$newWidth = $img->getWidth() / 1.2;
$newHeight = $watermark->getHeight() * ($newWidth / $watermark->getWidth());
$watermark->resize($newWidth, $newHeight);
}
if($watermark->getHeight() > $img->getHeight()) {
$newHeight = $img->getHeight() / 1.1;
$newWidth = $watermark->getWidth() * ($newHeight / $watermark->getHeight());
$watermark->resize($newWidth, $newHeight);
}
$watermark->opacity(40);
$img->insert($watermark, 'center');
$watermark->destroy();
return $img;
}
private function addWatermarkText(\Intervention\Image\Image $img, string $text) : \Intervention\Image\Image {
$img->resizeCanvas(0, 28, 'top', true, "#000000");
$img->text($text, $img->getWidth() - 10, $img->getHeight() - 25, function($font) {
$font->file(storage_path("OpenSans-Light.ttf"));
$font->size(18);
$font->color('#ffffff');
$font->align('right');
$font->valign('top');
});
return $img;
}
}