Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/Drivers/Vips/VipsDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ class VipsDriver implements ImageDriver

protected Image $image;

protected string $originalPath;

protected ?string $format = null;

protected int $defaultQuality = 75;
Expand Down Expand Up @@ -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
Expand All @@ -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();
Expand All @@ -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;
Expand All @@ -134,6 +141,8 @@ public function save(string $path = ''): static
$this->optimizerChain->optimize($path);
}

$this->format = null;

return $this;
}

Expand Down
11 changes: 11 additions & 0 deletions tests/ImageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand Down