Perfect Image Resize

A library for Laravel Framework


Introduction


Easy image resize is library developed for Laravel Framework. The main features are as follow:

Features

  1. Image resize, crop, fit, convas, center
  2. Adding water mark on image
  3. Image validation before upload & resize
  4. Directory structure auto generation
  5. Gives Pretty file name to image

This library may not be suitable for your project if you are really looking for advance image editing features.

Requirements

Before you install this library. You need to install following packages.

Intervention Image

This library used intervention image package. First install it with your Laravel application

Install intervention from GitHub

Perfect File Name

Perfect file name library generates pretty name for any file. It is recommended that you install this library.

Install Perfect File name from GitHub

Installation

Run following composer command to install package.

                        composer require salmanbe/resize
                    

There is a service provider included for integration with the Laravel framework. This service should automatically be registered else to register the service provider, add the following to the providers array in config/app.php:

                        Salmanbe\Resize\ResizeServiceProvider::class,
                    

You can also add it as a Facade in config/app.php:

                        'Resize' => Salmanbe\Resize\Resize::class,
                    

Generate configuration file with this command.

                        php artisan vendor:publish --provider="Salmanbe\Resize\ResizeServiceProvider"
                    

Configuration

In configuration file located at config/resize.php, you can define main configuration that will be applied to whole project. These configurations can be ovverdden that will be discussed later.

                        'mime_types' => [
                            'image/png',
                            'image/jpeg',
                            'image/gif'
                        ],
                    

Defining the image mime types. You can add or remove mime types. If no mime type is added then default image/png, image/jpeg and image/gif will be considered.

                        'original_name' => false,
                    

If set to true then system will use exact image file name. If not set or true then perfect file name library will be used.

                        'max_image_size' => 2,
                    

Maximum allowed uploaded image file size in MBs. If not set then default 2MB will be considered.

                        'resize_type' => 'canvas',
                    

The type of image resizing. Other possible positions are as follow:

  1. canvas
  2. resize
  3. fit
  4. crop
  5. original
  6. center
                        'water_mark_image' => public_path('assets/transparant.png'),
                    

Path to water mark image.

                        'water_mark_position' => 'top-center',
                    

Default water mark position. Other possible positions are as follow:

  1. top-left
  2. top-center
  3. top-right
  4. center
  5. bottom-left
  6. bottom-center
  7. bottom-right

Code Examples

Creating Instance

                        $image = new Resize($request->image);
                    

The resize part comes later. First we load options via class constructor.

                        $image = new Resize($request->image, []);
                    

You can optionally pass second array parameter to class constructor.

                        $image = new Resize($request->image, [
                                'original_name' => true
                        ]);
                    

If passed then system will use original name of the image. If you have already created configuration file then this argument will override it.

                        $image = new Resize($request->image, [
                                'max_image_size' => 2
                        ]);
                    

You can optionally pass size of allowed image file in MBs. If you have already defined max_image_size in resize.php configuration file then that value will be overridden. If there is no configuration file or if no default size added or if you don't pass this argument here then default 1MB maximum allowed size will be considered.

                        $image = new Resize($request->image, [
                                'resize_type' => 'canvas'
                        ]);
                    

You can optionally pass resize type. If you have already defined resize_type in resize.php configuration file then that value will be overridden. If there is no configuration file or if no default resize type added or if you don't pass this argument here then default type 'canvas' will be considered.

                        $image = new Resize($request->image, [
                                'water_mark_image' => public_path('pictures/transparant.png'),
                                'water_mark_position' => 'center'
                        ]);
                    

Global water mark options can be added via resize.php configuration file. Passing these values will override global configuration values.

                        $image = new Resize($request->image, [
                                'old_image' => 'visa-application.png'
                        ]);
                    

This option is no needed when you are adding a new record with image but if you already have a previously saved image in database table then this argument will delete old image and replace it.

                        $image = new Resize($request->image, [
                                'filename' => [
                                    'limit' => 200,
                                    'timestamp' => date('d-m-Y-His'),
                                    'slugify' => true,
                                    'separator' => '-',
                                    'uppercase' => true
                            ]
                        ]);
                    

If you are using salmanbe\filename library then you can pass these parameters to pretty design newly uploaded file name. Read more about Perfect Filename library

                        $image = new Resize($request->image, [
                                'original_name' => true,
                                'max_image_size' => 2, 
                                'resize_type' => 'canvas',
                                'water_mark_image' => public_path('pictures/transparant.png'),
                                'water_mark_position' => 'center'
                                'old_image' => 'visa-application.png'
                                'filename' => [
                                    'limit' => 200,
                                    'timestamp' => date('d-m-Y-His'),
                                    'slugify' => true,
                                    'separator' => '-',
                                    'uppercase' => true
                            ]
                        ]);
                    

Overview of all possible options.

Resizing Image

                        $image->resize(public_path('pictures/blog/small/'), 100, 50, []);
                        $image->resize(public_path('pictures/blog/medium/'), 400, 250, []);
                        $image->resize(public_path('pictures/blog/large/'), 768, 400, []);
                    

Above example generates 3 images of different sizes. First required parameter is path of directory where final image will be stored. If path does not exists then system will create it automatically. Second required parameter is resize width of the image. Third optional parameter is resize height of the image. Fourth array parameter is optional.

                        $image->resize(public_path('pictures/blog/small/'), 100);
                        $image->resize(public_path('pictures/blog/medium/'), 400, null, []);
                        $image->resize(public_path('pictures/blog/large/'), 768, 400, [
                                'water_mark' => true
                        ]);
                    

In above example the water mark is only added to large image.

Store Example

                        use Salmanbe\Resize\Resize;

                        /**
                        * This function saves new record to database from posted form values.
                        * @param  Illuminate\Http\Request $request
                        * @return  mixed
                        */
                       public function store(Request $request) {

                           $blog = $request->all();

                           if ($request->image) {

                               $image = new Resize($request->image);

                               if ($image->is_ok) {
                                   $image->resize(public_path('pictures/blog/small/'), 100); 
                                   $image->resize(public_path('pictures/blog/large/'), 768, 400);
                                   $blog['image'] = $image->new_image_name;
                               } else {
                                   $blog['image'] = null;
                               }
                           }

                           Blog::create($blog);

                           if (isset($image) && count($image->errors)) {
                               return redirect()->back()->with('error', implode('
', $image->errors)); } return redirect()->route('admin.blog.index')->with('success', 'Record updated'); }

In above example system first checks if image field exists in request. Then creates instance of class. if $image->is_ok returns true only then image will be uploaded and resized. The name of the new image will be saved in same $request->image that will be saved later to database table.

All errors of files can be accessed via $image->errors. You can convert it into a string and either send it back or save to log. If image is invalid then system will still save other blog parameters and will not block anything.

Update Example

                            use Salmanbe\Resize\Resize;

                            /**
                            * This function updates record to database from posted form values.
                            * @param  Illuminate\Http\Request $request
                            * @param  integer $id
                            * @return  mixed
                            */
                           public function update(Request $request, $id) {

                               $blog = Blog::findOrFail($id);
                               $old_image = $blog->image;
                               $blog->fill($request->all());

                               if ($request->image) {

                                   $image = new Resize($request->image, [
                                       'old_image' => $old_image
                                   ]);

                                   if ($image->is_ok) {

                                       $image->resize(public_path('pictures/blog/small/'), 100); 
                                       $image->resize(public_path('pictures/blog/large/'), 768, 400);
                                       $blog->image = $image->new_image_name;
                                   }
                               }

                               $blog->save();

                               if (isset($image) && count($image->errors)) {
                                   return redirect()->back()->with('error', implode('
', $image->errors)); } return redirect()->back()->with('success', 'Record updated'); }

Update function is almost similar to store function however, 'old_image' => $blog->image will delete the previously saved image name from the disk.


Issues & Solutions

Uploading and resizing images can be a heavy process specially if your system does not have enough resources and you are uploading large images. In such cases system may crash and show 500 error. There are some solutions that can help:

Increase Resources

Try increasing following resources from php.ini.

  1. max_execution_time
  2. memory_limit
  3. post_max_size
  4. upload_max_filesize

Enable ImageMagick instead of GD Library

If you are working on your local system and don't have installed ImageMagick library then keep using GD library. But when you make your project live then use ImageMagick library. This magical library has wonderful memory management system and it does everything without taking much system resources. You can change library option from configuration file of intervention image package.

Report A Bug

If you encounter a bug then send me an email to salman@salman.be with as much information as you can.

Uninstall

                        Salmanbe\Resize\ResizeServiceProvider::class,
                    

Remove it from app.config file if added.

                        'Resize' => Salmanbe\Resize\Resize::class
                    

Remove it from app.config file if added.

                        composer remove salmanbe/resize
                    

Finally run this command.

License

Copyright (c) 2021 Salman Javaid (https://www.salman.be)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.