Resize Images in CodeIgniter 4 Before Uploading to Server

Share this Article
Reading Time: 10 minutes
453 Views

Resizing Images before upload is a very primary topic but in this topic many developers get stuck. When we upload image it will be of any size but we need to resize it first before upload.

In this article, we will see the entire concept of CodeIgniter 4 to generate thumbnail images without using any jquery plugin or doing some extra effort to resize and upload images in the CodeIgniter 4 project.

This article is totally from scratch. All steps will be super easy to understand. We will upload an image, resize, upload to server and then save to database table.

Here, we have more articles on Image manipulation Class of CodeIgniter 4.

  • Rotate Image in CodeIgniter 4, Click here.
  • Add a text watermark on Images in CodeIgniter 4, Click here.

Let’s see the topic Resize Images in CodeIgniter 4 before uploading to server.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Turn Development Mode On

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


Create Database & Tables To Application

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.

Next, we need to create a table inside database.

CREATE TABLE `products` (
 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(120) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` text COLLATE utf8mb4_unicode_ci NOT NULL,
 `image` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `thumbnail` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `cost` int(11) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 
#--------------------------------------------------------------------
# DATABASE
#-------------------------------------------------------------------- 
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Now, database successfully connected with application.


Needed PHP Extension Before Work

While working with image related stuff in PHP, make sure your PHP version should have these two most common image processing libraries GD Library and Imagick extensions enabled.

Whether your system already contains these extensions or not you can verify like this –

  • Create info.php file at your localhost directory
  • <?php phpinfo(); ?> Add this code into info.php file.
  • Run this file into browser

You should see these information into php information page.

GD Extension Enabled

Imagick Extension Enabled

So, these two extensions we need, if you don’t have. Please install it first.


Create Model

We need very first a Model.

Open project into terminal and run this spark command.

$ php spark make:model Product --suffix

It will create a model i.e ProductModel.php at /app/Models folder.

Open ProductModel.php and write this complete code into it.

<?php

namespace App\Models;

use CodeIgniter\Model;

class ProductModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'products';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [
		'name',
		'description',
		'image',
        'thumbnail',
        'cost'
	];

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];
}

Create Controller

We need now a controller file. Back to terminal and run this spark command to create.

$ php spark make:controller Product --suffix

This will creates a file ProductController.php at /app/Controllers folder.

Open ProductController.php and write this complete code into it,

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\ProductModel;

class ProductController extends BaseController
{
	public function index()
	{
		if ($this->request->getMethod() == "post") {

			$rules = [
				"name" => "required|min_length[3]|max_length[40]",
				"description" => "required",
				"image" => [
					"rules" => "uploaded[image]|max_size[image,1024]|is_image[image]|mime_in[image,image/jpg,image/jpeg,image/gif,image/png]",
					"label" => "Product Image",
				],
				"cost" => "required"
			];

			if (!$this->validate($rules)) {

				return view("add-product", [
					"validation" => $this->validator,
				]);
			} else {

				$file = $this->request->getFile("image");

				$session = session();
				$image = $file->getName();

				if ($file->move("images", $image)) {

					// thumnail images path
					$thumbnail_path = "thumbnails";

					// resizing image
					\Config\Services::image()->withFile('images/' . $image)
						->resize(200, 100, true, 'height')
						->save($thumbnail_path . '/' . $image);

					$productModel = new ProductModel();

					$data = [
						"name" => $this->request->getVar("name"),
						"description" => $this->request->getVar("description"),
						"cost" => $this->request->getVar("cost"),
						"image" => "/images/" . $image,
						"thumbnail" => "/thumbnails/" . $image,
					];

					if ($productModel->insert($data)) {

						$session->setFlashdata("success", "Product created successfully");
					} else {

						$session->setFlashdata("error", "Failed to create product");
					}
				}
			}
			redirect('add-product');
		}

		return view("add-product");
	}
}
  • When we upload image, image resize code will convert image into it’s thumbnail as well.
  • So we will get two different images. Original image inside /images folder and thumbnail image inside /thumbnails folder.

Create Layout File

Go inside /app/Views folder and create a file add-product.php. Open this file and write this complete code into it.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Resize Images in CodeIgniter 4 Before Uploading to Server</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <style>
        .errors li {
            color: red;
        }
    </style>
</head>

<body>

    <div class="container">
        <h2 style="text-align: center;">Resize Images in CodeIgniter 4 Before Uploading to Server</h2>
        <div class="panel panel-primary">
            <div class="panel-heading">Resize Images in CodeIgniter 4 Before Uploading to Server</div>
            <div class="panel-body">

                <?php if (session()->get("success")) { ?>
                    <div class="alert alert-success">
                        <?= session()->get("success") ?>
                    </div>
                <?php } ?>

                <?php
                // To print error messages
                if (isset($validation)) {

                    print_r($validation->listErrors());
                }
                ?>

                <form action="<?= base_url('add-product') ?>" enctype="multipart/form-data" method="post">
                    <div class="form-group">
                        <input type="text" name="name" class="form-control" placeholder="Name">
                    </div>
                    <div class="form-group">
                        <textarea name="description" class="form-control" placeholder="Description"></textarea>
                    </div>
                    <div class="form-group">
                        <input type="file" name="image" class="form-control" class="image">
                    </div>
                    <div class="form-group">
                        <input type="number" min="0" name="cost" class="form-control" placeholder="Cost">
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn btn-success">Save</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

</body>

</html>

Create Images Folders

We need to create two folders inside /public folder which is at root.

  • images folder inside as /public/images – It will store original images
  • thumbnails inside as /public/thumbnails – It will store thumbnail images.

Create Route

Open Routes.php from /routes folder and add this route into it.

//...

$routes->match(["get", "post"], "add-product", "ProductController::index");

Application Testing

Start development server:

$ php spark serve

URL: http://localhost:8080/add-product

Form submit with no data in inputs fields.

After data save to database table

We hope this article helped you to learn Resize Images in CodeIgniter 4 Before Uploading to Server Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

Leave a Comment