Search code examples
laravelintervention

Laravel image intervention resize and put in storage


When a user uploads a picture I want to store it in multiple formats. My code for handling the image:

$img = Image::make($file)->encode('png');
if($img->width()>3000){
    $img->resize(3000, null, function ($constraint) {
        $constraint->aspectRatio();
    });
}
if($img->height()>3000){
    $img->resize(null, 3000, function ($constraint) {
        $constraint->aspectRatio();
    });
}
$uid = Str::uuid();
$fileName = Str::slug($item->name . $uid).'.png';

$high =  clone $img;
Storage::put(  $this->getUploadPath($bathroom->id, $fileName, "high"), $high);


$med =  clone  $img;
$med->fit(1000,1000);

Storage::put(  $this->getUploadPath($bathroom->id, $fileName, "med"), $med);

$thumb = clone   $img;
$thumb->fit(700,700);
Storage::put(  $this->getUploadPath($bathroom->id, $fileName, "thumb"), $thumb);

As you see I tried a few variations.

I also tried:

    $thumb = clone   $img;
    $thumb->resize(400, 400, function ($constraint) {
        $constraint->aspectRatio();
    });
    Storage::put(  $this->getUploadPath($fileName, "thumb"), $thumb);

The getUploadPath function:

public function  getUploadPath($id, $filename, $quality = 'high'){
    return 'public/img/bathroom/'.$id.'/'.$quality.'/'.$filename;
}

I want the image to fit in xpx x xpx without scaling or downgrading quality. The images are created and stored as expected but the image is not resized. How can I make the image resize?


Solution

  • You need to stream it ($thumb->stream();) before saving by Storage facade as below:

    $thumb = clone   $img;
    $thumb->resize(400, 400, function ($constraint) {
        $constraint->aspectRatio();
    });
    
    $thumb->stream();
    
    Storage::put(  $this->getUploadPath($fileName, "thumb"), $thumb);