5

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?

Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169

3 Answers3

4

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);
SEYED BABAK ASHRAFI
  • 4,093
  • 4
  • 22
  • 32
0

You need to use the save($img) method to actually create the resized image.

This is what the official docs have to say about this -

To create actually image data from an image object, you can access methods like encode to create encoded image data or use save to write an image into the filesystem. It's also possible to send an HTTP response with current image data.

Image::make('foo.jpg')->resize(300, 200)->save('bar.jpg');

Details on the method in the official docs - http://image.intervention.io/api/save

Qumber
  • 13,130
  • 4
  • 18
  • 33
-1
     if ($request->hasFile('image-file')) {
        $image      = $request->file('image-file');
        $fileName   = 'IMG'.time() . '.' . $image->getClientOriginalExtension();

        $img = Image::make($image->getRealPath());
        $img->resize(400, 400, function ($constraint) {
            $constraint->aspectRatio();                 
        });

        $img->stream();

        Storage::disk('local')->put('public/img/bathroom/'.'/'.$fileName, $img, 'public');
     }

Hope this works for you!!

Ankit Jindal
  • 3,672
  • 3
  • 25
  • 37