Resize Images in CodeIgniter 4 Before Uploading to Server

Reading Time: 9 minutes
7,684 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.

Learn More –

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Environment (.env) Setup

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

Either we can do via renaming file as simple as that. Also we can do by terminal command.

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.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database

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

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


Create Database Table

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 Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string values.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = admin
database.default.password = admin
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
  

Now, database successfully connected with the 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

Open project terminal and start development server via command:

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.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more