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, adjust the quality, rotate, crop, and add a watermark to the image.

This tool works smoothly with both GD and ImageMagick libraries.

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


Table of Content

  1. Create Controller – Upload and resize Image
  2. Routes
  3. Create View
  4. Output
  5. Conclusion

1. Create Controller – Upload and resize Image

  • Create the ImagesController by running the command:
php spark make:controller ImagesController
  • Then, open app/Controllers/ImagesController.php file.

Inside this controller, set up two methods:

  • index() – This method loads index view.
  • uploadfile() – This method is triggered when the form is submitted.

Implement file validation. If the file doesn’t meet the criteria, return to the page with an error message.

If the file is valid, upload it to the uploads folder.

Resize Image –

After uploading the file, it’s time to resize it. To do this, create an object of \Config\Services::image(). Specify the location to store the resized image in the $resize_location variable. Check if this location exists; if not, 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

Make a new file called index.php inside the app/Views/ folder.

If a SESSION is set, show a notification using Bootstrap alert.

Next, build a form by setting 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

CodeIgniter 4’s Image Manipulation class empowers you to easily customize images—resizing, adjusting quality, and more. With seamless compatibility with GD and ImageMagick, it’s a versatile tool.

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