Laravel 图片介入调整大小入库

Laravel image intervention resize and put in storage

当用户上传图片时,我想以多种格式存储它。 我处理图像的代码:

$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);

如您所见,我尝试了一些变体。

我也试过:

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

getUploadPath 函数:

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

我希望图像适合 xpx x xpx,而不缩放或降低质量。 图像已按预期创建和存储,但未调整图像大小。如何调整图片大小?

您需要使用 save($img) 方法来实际创建调整大小的图像。

官方文档是这么说的-

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');

官方文档中的方法详情 - http://image.intervention.io/api/save

在通过 Storage facade 保存之前,您需要对其进行流式传输 ($thumb->stream();),如下所示:

$thumb = clone   $img;
$thumb->resize(400, 400, function ($constraint) {
    $constraint->aspectRatio();
});

$thumb->stream();

Storage::put(  $this->getUploadPath($fileName, "thumb"), $thumb);
     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');
     }

希望这对你有用!!