In my understanding of the code below, the value of $image should be always the same (original value passed to the function), but surprisingly for me it keeps changing (the value of the first dd() is different from the second), resulting in worse quality images each time the resize() method is called. Shouldn't saving the resized value in a different variable(ex:$imageSmallJpg) keep $image immutable during the function execution?
private function saveTransformedImages($image, $imagePath, $storageDrive)
{
dd($image);
$imageName = pathinfo($image->getClientOriginalName(), PATHINFO_FILENAME);
$imageSmallJpg = $this->resize($image, 500);
$imgSaveName = $imageName . '-sm.jpg';
Storage::disk($storageDrive)->put($imagePath . '/' . $imgSaveName, $imageSmallJpg);
$imageSmallWebp = $this->convertToWebp($imageSmallJpg);
$imgSaveName = $imageName . 'sm-.webp';
Storage::disk($storageDrive)->put($imagePath . '/' . $imgSaveName, $imageSmallWebp);
dd($image);
$imageMediumJpg = $this->resize($image, 960);
$imgSaveName = $imageName . '-md.jpg';
Storage::disk($storageDrive)->put($imagePath . '/' . $imgSaveName, $imageMediumJpg);
$imageMediumWeb = $this->convertToWebp($imageSmallJpg);
$imgSaveName = $imageName . '-md.webp';
Storage::disk($storageDrive)->put($imagePath . '/' . $imgSaveName, $imageMediumWeb);
$imageLargeJpg = $this->resize($image, 1300);
$imgSaveName = $imageName . '-lg.jpg';
Storage::disk($storageDrive)->put($imagePath . '/' . $imgSaveName, $imageLargeJpg);
$imageLargeWebp = $this->convertToWebp($imageSmallJpg);
$imgSaveName = $imageName . 'lg-.webp';
Storage::disk($storageDrive)->put($imagePath . '/' . $imgSaveName, $imageLargeWebp);
}
related methods:
public function resize($image, $maxWidth)
{
$img = Image::make($image);
$img->resize($maxWidth, null, function ($constraint) {
$constraint->aspectRatio();
});
$img = $img->save(null, 70, 'jpg');
return $img;
}
public function convertToWebp($image)
{
$webp = $image->save(null, 70, 'webp');
return $webp;
}
CodePudding user response:
Calling save
on the Intervention Image object that is created after the Image::make
calls will save the data to the disk. So the uploaded file data on disk is being overwritten when you call save(null, ...)
as it will just save to the current path. Then you are calling Image::make
with that path so it is now loading that file again (which has new data - resized) instead of the original (which doesn't exist on the filesystem any more).
Just remove the save
calls and if you want to encode the image you can call encode
directly (since save
calls encode
before writing to disk any way). This should avoid the issue of the data being overwritten.
On a side note, you can actually do all of this resizing and encoding with one single Intervention Image object without having to keep reloading the data from disk by calling Image::make
over and over again (you can have just 1 call to Image::make
).