【问题标题】:Laravel image intervention resize and put in storageLaravel 图像干预调整大小并入库
【发布时间】:2020-07-12 09:57:35
【问题描述】:

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

$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();吗?

标签: laravel intervention


【解决方案1】:

您需要先流式传输($thumb->stream();),然后通过Storage 外观保存,如下所示:

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

$thumb->stream();

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

【讨论】:

    【解决方案2】:

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

    这是官方文档对此的看法 -

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

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

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

    【讨论】:

    • save如何入库?
    • save() 只是在调整大小后创建新图像。您仍然需要使用Storage::put 将其放入存储中。
    【解决方案3】:
         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');
         }
    

    希望这对你有用!!

    【讨论】:

      猜你喜欢
      • 2017-03-28
      • 2018-09-21
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      • 2018-09-23
      相关资源
      最近更新 更多