php 在使用存储功能存储到服务器之前减小图像大小

3phpmpom  于 2023-06-20  发布在  PHP
关注(0)|答案(2)|浏览(105)

早上好
我想在将图像保存到存储文件夹之前减小图像的大小
下面是我函数的代码谢谢大家的支持

public static function pre_update($Model, $data, $id)
     {
         $m = $Model::find($id);
         if ($m) {
             $field = $m->getFillable();
             $name = explode("App\\", $Model)[1];
             foreach ($data as $key => $value) {
                 if (in_array($key, $field)) {
                     if (in_array($key, $m->getFiles())) {
                         $fop =$m->getOriginal()[$key];
                         if (Storage::has($fop))
                             Storage::delete($fop);

                         $image = $value;
                         $fpath = "img/" . strtolower($name) . "/" . uniqid() . '_' . $image->getClientOriginalName();
                         $m->$key = $fpath;
                         Storage::put($fpath, File::get($image));

                     } else {
                         $m->$key = $value;
                     }
                 }
             }
             return $m;
         } else {
             return null;
         }
     }
9fkzdhlc

9fkzdhlc1#

您可以使用Imagine库。安装wia composer“composer require imagine/imagine”它应该看起来像这样:

require 'vendor/autoload.php';

public static function pre_update($Model, $data, $id)
     {
         $imagine = new Imagine\Gd\Imagine();
         $m = $Model::find($id);
         if ($m) {
             $field = $m->getFillable();
             $name = explode("App\\", $Model)[1];
             foreach ($data as $key => $value) {
                 if (in_array($key, $field)) {
                     if (in_array($key, $m->getFiles())) {
                         $fop =$m->getOriginal()[$key];
                         if (Storage::has($fop))
                             Storage::delete($fop);

                         $image = $value;
                         $fpath = "img/" . strtolower($name) . "/" . uniqid() . '_' . $image->getClientOriginalName();
                         $m->$key = $fpath;
                         $imagine->open($image)->resize(new Imagine\Image\Box(220, 220))->save($m->$key);

                     } else {
                         $m->$key = $value;
                     }
                 }
             }
             return $m;
         } else {
             return null;
         }
     }
dwbf0jvd

dwbf0jvd2#

您应该使用包干预它将帮助您减少大小和尺寸的照片,使存储更容易
这里是文档链接intervention

相关问题