ImageProcessingService.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace App\Services;
  3. use Intervention\Image\ImageManager;
  4. use Intervention\Image\Drivers\Gd\Driver;
  5. use Illuminate\Support\Facades\Storage;
  6. class ImageProcessingService
  7. {
  8. protected $manager;
  9. public function __construct()
  10. {
  11. $this->manager = new ImageManager(new Driver());
  12. }
  13. /**
  14. * Crop an image based on the given coordinates.
  15. *
  16. * @param string $sourcePath Absolute path to the source image.
  17. * @param int $yMin Starting Y coordinate.
  18. * @param int $yMax Ending Y coordinate.
  19. * @param string $outputPath Absolute path to save the cropped image.
  20. * @return bool True on success, false on failure.
  21. */
  22. public function cropImage(string $sourcePath, int $yMin, int $yMax, string $outputPath): bool
  23. {
  24. try {
  25. if (!file_exists($sourcePath)) {
  26. throw new \Exception("Source image not found: {$sourcePath}");
  27. }
  28. $image = $this->manager->read($sourcePath);
  29. $width = $image->width();
  30. $height = $image->height();
  31. // Validate coordinates
  32. $yMin = max(0, $yMin);
  33. $yMax = min($height, $yMax);
  34. $cropHeight = $yMax - $yMin;
  35. if ($cropHeight <= 0) {
  36. throw new \Exception("Invalid crop height: {$cropHeight} (yMin: {$yMin}, yMax: {$yMax})");
  37. }
  38. // Crop the full width of the image for the given Y range
  39. $image->crop($width, $cropHeight, 0, $yMin);
  40. $image->save($outputPath);
  41. return true;
  42. } catch (\Exception $e) {
  43. \Log::error("Image cropping failed: " . $e->getMessage());
  44. return false;
  45. }
  46. }
  47. }