How to Upload and Resize Image in CodeIgniter 4

CodeIgniter 4 already has an Image Manipulation class for customizing images. With this, you can resize, change quality, rotate, crop, and add a watermark to the image.

It supports GD and ImageMagick library.

In this tutorial, I show how you can upload and resize image dimensions in CodeIgniter 4.

How to Upload and resize image in CodeIgniter 4


Contents

  1. Create Controller
  2. Routes
  3. Create View
  4. Output
  5. Conclusion

1. Create Controller

  • Create ImagesController Controller –
php spark make:controller ImagesController
  • Open app/Controllers/ImagesController.php file.

Create 2 methods –

  • index() – Load index view.
  • uploadfile() – This method calls on <form > submit.

Define validation for the file. If file is not validated then return to the page with an error message.

If validated then upload the file to uploads folder.

Resize Image –

After file upload resize the image.

Create object of \Config\Services::image(). In $resize_location assign resize image file store location. Check whether the location is available or not. If not available then create it.

$image = \Config\Services::image(); 

$image->withFile('../public/uploads/'.$newName) 
      ->resize(320, 240, true, 'width') 
      ->save('../public/thumbnail/'.$newName);

In the withFile() pass the uploaded file path.

In resize() pass 4 parameters –

    • Image new width.
    • Image new height.
    • Set it to true if you want to maintain the aspect ratio of the image.
    • According to which axis do you want to maintain the aspect ratio. It takes width or height as parameter. If the 3rd is set to false then there will be no effect of this 4th parameter.

Call save() to store the created file.

Completed Code

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class ImagesController extends BaseController
{
     public function index(){
          return view('index'); 
     }

     public function uploadfile(){
          $request = service('request');

          ## Validation
          $validation = \Config\Services::validation();

          $input = $validation->setRules([
               'file' => 'uploaded[file]|max_size[file,2048]|ext_in[file,jpeg,jpg,png],'
          ]);

          if ($validation->withRequest($this->request)->run() == FALSE){

               $data['validation'] = $this->validator;
               return redirect()->back()->withInput()->with('validation', $this->validator);

          }else{

               if($file = $this->request->getFile('file')) {
                     if ($file->isValid() && ! $file->hasMoved()) {

                          // Get file name and extension
                          $filename = $file->getName();
                          $ext = $file->getClientExtension();

                          // Get random file name
                          $newName = $file->getRandomName();

                          // Store file in public/uploads/ folder
                          $upload_location = "../public/uploads/";
                          $file->move($upload_location, $newName);

                          // File path to display preview
                          $filepath = base_url()."/uploads/".$newName;

                          // Resize image
                          $resize_location = "../public/thumbnail/";
                          if (!is_dir($resize_location)) {
                                mkdir($resize_location, 0777, TRUE);
                          }

                          $image = \Config\Services::image();
                          $image->withFile($upload_location.$newName)
                                ->resize(320, 240, true, 'width')
                                ->save($resize_location.$newName);

                          // Set Session
                          session()->setFlashdata('message', 'File uploaded successfully.');
                          session()->setFlashdata('alert-class', 'alert-success');

                     }else{
                          // Set Session
                          session()->setFlashdata('message', 'File not uploaded.');
                          session()->setFlashdata('alert-class', 'alert-danger');
                     }
               }else{
                     // Set Session
                     session()->setFlashdata('message', 'File not uploaded.');
                     session()->setFlashdata('alert-class', 'alert-danger');
               }
          }
          return redirect()->route('/');
     }
}

2. Routes

  • Open app/Config/Routes.php file.
  • Define 2 routes –
    • / – Display upload form.
    • image/uploadfile – Upload the file.
$routes->get('/', 'ImagesController::index');
$routes->post('image/uploadfile', 'ImagesController::uploadfile');

3. Create View

Create index.php file in app/Views/ folder.

Display bootstrap alert if SESSION is set.

Create a <form > and set its action to site_url('image/uploadfile'). In the <form > create a file element and a submit button.

Completed Code

<!DOCTYPE html>
<html>
<head>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <title>How to Upload and Resize Image in CodeIgniter 4</title>

     <!-- Bootstrap CSS -->
     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" >
</head>
<body>

     <div class="container">

          <div class="row">
                <div class="col-md-6 mt-5" style="margin: 0 auto;">

                    <?php 
                    // Display Response
                    if(session()->has('message')){      
                    ?>
                         <div class="alert <?= session()->getFlashdata('alert-class') ?>">
                              <?= session()->getFlashdata('message') ?>
                         </div>
                    <?php
                    }
                    ?>

                    <?php $validation = \Config\Services::validation(); ?>

                    <form method="post" action="<?=site_url('image/uploadfile')?>" enctype="multipart/form-data">

                         <?= csrf_field(); ?>

                         <div class="form-group mb-4">
                              <label class="control-label col-sm-2" for="file">File:</label>
                              <div class="col-sm-10">
                                    <input type="file" class="form-control" id="file" name="file" >
                              </div>

                              <!-- Error -->
                              <?php if( $validation->getError('file') ) {?>
                                    <div class='text-danger mt-2'>
                                         * <?= $validation->getError('file'); ?>
                                    </div>
                              <?php }?>
                         </div>

                         <div class="form-group "> 
                              <div class="col-sm-offset-2 col-sm-10">
                                    <button type="submit" class="btn btn-info">Submit</button>
                              </div>
                         </div>
                    </form>
                </div>
          </div>

     </div>
</body>
</html>

4. Output

View Output


5. Conclusion

For example purpose, I saved the resized image file to a different location but you can replace the existing file if you want.

If you found this tutorial helpful then don't forget to share.

Leave a Comment