diff --git a/src/Drivers/Vips/VipsDriver.php b/src/Drivers/Vips/VipsDriver.php index b3ab27b..9e44431 100644 --- a/src/Drivers/Vips/VipsDriver.php +++ b/src/Drivers/Vips/VipsDriver.php @@ -42,6 +42,8 @@ class VipsDriver implements ImageDriver protected Image $image; + protected string $originalPath; + protected ?string $format = null; protected int $defaultQuality = 75; @@ -81,6 +83,7 @@ protected function setImage(Image $image): static public function loadFile(string $path, bool $autoRotate = true): static { $this->optimize = false; + $this->originalPath = $path; // Use 'access' => 'sequential' to avoid libvips file caching issues // when the same file path is overwritten between loads @@ -103,7 +106,11 @@ public function driverName(): string public function save(string $path = ''): static { - $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION)); + if (! $path) { + $path = $this->originalPath; + } + + $extension = $this->format ?? strtolower(pathinfo($path, PATHINFO_EXTENSION)); if ($this->quality && $extension === 'png') { throw CannotOptimizePng::make(); @@ -124,7 +131,7 @@ public function save(string $path = ''): static if (str_contains($message, 'is not a known file format') || str_contains($message, 'unsupported') || str_contains($message, 'unable to call')) { - throw UnsupportedImageFormat::make($extension ?: $this->format ?? 'unknown', $exception); + throw UnsupportedImageFormat::make($extension ?: 'unknown', $exception); } throw $exception; @@ -134,6 +141,8 @@ public function save(string $path = ''): static $this->optimizerChain->optimize($path); } + $this->format = null; + return $this; } diff --git a/tests/ImageTest.php b/tests/ImageTest.php index 7557645..58b8d82 100644 --- a/tests/ImageTest.php +++ b/tests/ImageTest.php @@ -61,6 +61,17 @@ expect($targetImage->getWidth())->toEqual(200); }); +it('can save without a path to overwrite the original file', function (ImageDriver $driver) { + $targetFile = $this->tempDir->path("{$driver->driverName()}/save-without-path.jpg"); + + copy(getTestJpg(), $targetFile); + + $driver->loadFile($targetFile)->greyscale()->save(); + + expect($targetFile)->toBeFile(); + expect($targetFile)->toHaveMime('image/jpeg'); +})->with('drivers'); + it('works with transparent pngs', function (ImageDriver $driver) { $targetFile = $this->tempDir->path("{$driver->driverName()}/saving-transparent-png.png");