oc-resizer-plugin/compressors/PdfCompressor.php

78 lines
2.0 KiB
PHP
Raw Normal View History

2021-09-17 14:22:19 +02:00
<?php
namespace Aweos\Resizer\Compressors;
use Aweos\Resizer\Exceptions\ResizerException;
2021-09-17 14:22:19 +02:00
use Illuminate\Support\Collection;
use Intervention\Image\ImageManager;
use Storage;
2021-09-17 17:09:17 +02:00
class PdfCompressor extends Compressor
{
public function getExtensionRegex(): string
{
return 'pdf\.jpg';
}
2021-09-17 14:22:19 +02:00
protected function getExtension(): string
{
2021-09-17 14:28:41 +02:00
return 'pdf.jpg';
2021-09-17 14:22:19 +02:00
}
public function make(string $path): array
{
$output = $this->tmpPath();
$mimetype = mime_content_type($path);
system('imagemin '.escapeshellarg($path).' --plugin=jpegtran --plugin=mozjpeg --plugin.mozjpeg.quality=70 > '.escapeshellarg($output));
system("mv ".escapeshellarg($output)." ".escapeshellarg($path));
return [
$path => [$path],
];
}
private function extractImage(string $pdf): string
{
2021-09-17 14:28:41 +02:00
$file = $this->tmpPath().'.'.$this->getExtension();
2021-09-17 14:22:19 +02:00
exec('convert -density 150 '.escapeshellarg($pdf.'[0]').' -quality 90 '.escapeshellarg($file), $output, $r);
if (!file_exists($file)) {
throw new ResizerException('File cannot be generated from PDF file. Root file is "'.$pdf.'"');
}
2021-09-17 14:22:19 +02:00
return $file;
}
public function originalSize(): array
{
$filename = $this->extractImage($this->media->root());
$size = getimagesize($filename);
@unlink($file);
return $size;
2021-09-17 14:22:19 +02:00
}
public function shouldGenerateVersions(): bool
{
return true;
}
public function resize(string $source, string $destination, Collection $size): void
{
$temp = $this->extractImage($source);
$r = app(ImageManager::class)->make($temp)
->fit($size->get('width'), $size->get('height'), fn ($constraint) => $constraint->upsize())
->save($temp);
list($destWidth, $destHeight) = getimagesize($temp);
$versionFilename = $destination.'/'.$this->versionFilename($source, $destWidth, $destHeight);
Storage::put($versionFilename, file_get_contents($temp));
}
}