skip to Main Content

Good morning,

I would like to reduce the size of the image before saving it in the storage folder

Below is the code of my function
thank you for your support

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

2

Answers


  1. You should use package Intervention
    It will help you reduce the size and dimensions of the photos and make storage easier

    Here is the documentation link
    intervention

    Login or Signup to reply.
  2. You can use the library Imagine.
    Install wia composer "composer require imagine/imagine"
    It should look like this:

    require 'vendor/autoload.php';
    
    public static function pre_update($Model, $data, $id)
         {
             $imagine = new ImagineGdImagine();
             $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 ImagineImageBox(220, 220))->save($m->$key);
    
                         } else {
                             $m->$key = $value;
                         }
                     }
                 }
                 return $m;
             } else {
                 return null;
             }
         }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search