ImageResizePipeline.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace App\Jobs\GroupsPipeline;
  3. use App\Models\GroupMedia;
  4. use App\Util\Media\Image;
  5. use Illuminate\Bus\Queueable;
  6. use Illuminate\Contracts\Queue\ShouldQueue;
  7. use Illuminate\Foundation\Bus\Dispatchable;
  8. use Illuminate\Queue\InteractsWithQueue;
  9. use Illuminate\Queue\SerializesModels;
  10. use Log;
  11. use Storage;
  12. use Image as Intervention;
  13. class ImageResizePipeline implements ShouldQueue
  14. {
  15. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  16. protected $media;
  17. /**
  18. * Delete the job if its models no longer exist.
  19. *
  20. * @var bool
  21. */
  22. public $deleteWhenMissingModels = true;
  23. /**
  24. * Create a new job instance.
  25. *
  26. * @return void
  27. */
  28. public function __construct(GroupMedia $media)
  29. {
  30. $this->media = $media;
  31. }
  32. /**
  33. * Execute the job.
  34. *
  35. * @return void
  36. */
  37. public function handle()
  38. {
  39. $media = $this->media;
  40. if(!$media) {
  41. return;
  42. }
  43. if (!Storage::exists($media->media_path) || $media->skip_optimize) {
  44. return;
  45. }
  46. $path = $media->media_path;
  47. $file = storage_path('app/' . $path);
  48. $quality = config_cache('pixelfed.image_quality');
  49. $orientations = [
  50. 'square' => [
  51. 'width' => 1080,
  52. 'height' => 1080,
  53. ],
  54. 'landscape' => [
  55. 'width' => 1920,
  56. 'height' => 1080,
  57. ],
  58. 'portrait' => [
  59. 'width' => 1080,
  60. 'height' => 1350,
  61. ],
  62. ];
  63. try {
  64. $img = Intervention::make($file);
  65. $img->orientate();
  66. $width = $img->width();
  67. $height = $img->height();
  68. $aspect = $width / $height;
  69. $orientation = $aspect === 1 ? 'square' : ($aspect > 1 ? 'landscape' : 'portrait');
  70. $ratio = $orientations[$orientation];
  71. $img->resize($ratio['width'], $ratio['height']);
  72. $img->save($file, $quality);
  73. } catch (Exception $e) {
  74. Log::error($e);
  75. }
  76. }
  77. }