Laravel 图片处理:利用 Image Intervention 调整大小并存储

5
当用户上传一张图片时,我想要将它以多种格式存储。以下是我处理图片的代码:
$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 的大小。 图片已按预期创建和存储,但图片未被调整大小。我该如何使图片调整大小?


你尝试过 $img->save(); 吗? - jewishmoses
3个回答

4

在使用 Storage 门面之前,您需要通过 ($thumb->stream();) 对其进行流式传输并按如下方式保存:

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

$thumb->stream();

Storage::put(  $this->getUploadPath($fileName, "thumb"), $thumb);

0

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

这是官方文档对此的说明 -

要从图像对象创建实际的图像数据,您可以访问encode等方法来创建编码的图像数据,或使用save将图像写入文件系统。还可以使用当前图像数据发送HTTP响应。

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

官方文档中有关该方法的详细信息 - http://image.intervention.io/api/save


如何将保存的数据放入存储中? - Sven van den Boogaart
save() 只是在你调整大小后创建新图像。你仍然需要使用 Storage::put 将其放入存储中。 - Qumber

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

希望这对你有用!!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接