You can manipulate the image after uploading it in Codeigniter 4. There is no package or third-party library for it. The CodeIgniter 4 provides the image manipulation class. Through this class, you can manipulate images as per your need. You can set a watermark on the uploaded image. You can resize, and crop the image also. In this post, you will get to know how to resize image in CodeIgniter 4. We will see these options one by one by applying them to the image. We have already seen the Image upload in CodeIgniter 4. So, let’s start by creating a new project in CodeIgniter 4. The image manipulation will help to reduce the image size. The image manipulation provides various options for the uploaded images. These options are available with this class-
- Image resizing,
- Thumbnail creation,
- Image cropping,
- Image rotating.
By resizing the image, you can compress and reduce the image size as well. It will boost the speed of the application also.
Prerequisites
We are going to create a new project in CodeIgniter 4. There are two ways to have a Codeigniter 4 project setup. Either you may download the setup directly from the official website of CodeIgniter. Or you can install it using the composer. I will prefer the composer.
Also, you will require the below configuration for the CodeIgniter 4 project setup.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Project Setup To Resize Image in CodeIgniter 4
At the very step, open the terminal or command prompt whatever you have. Now, hit the below command.
composer create-project codeigniter4/appstarter ci4-image-resize
This will install CodeIgniter 4. It may take a couple of minutes to setup the project. It depends upon your internet speed as well.
Once, you have the project, let’s do the environment configuration. This will enable the project to run it locally.
Configure Project Environment in CodeIgniter 4
Before doing any configuration, you need to open the project in a code editor. I will prefer VS Code. Once, you have opened the project, let’s navigate to the env file. So, at the very first step, you will need to rename it to .env. Now, open this file and search for the Environment configuration.
Under the environment section, you will see the CI_ENVIRONMENT. By default its value is production. But, we have to run the project in the local environment. Hence, this will require to be renamed as development.
#--------------------------------------------------------------------
# ENVIRONMENT
#--------------------------------------------------------------------
CI_ENVIRONMENT = development
Next, we have to do the setup for the database. Hence, create a new database in MySQL.
Create and Configure Database in CodeIgniter 4
Firstly, you need to have a database. I have created a new database using the below command.
CREATE DATABASE ci4_image
After creating the database, let’s come back to the project environment. Scroll down and come to the Database section. Now, you will have to configure the database as shown below.
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
database.default.hostname = localhost
database.default.database = ci4_image
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
Now, you are done with the database configuration.
In the next step, you will need to create a migration file for the table.
Login and Registration Authentication in Codeigniter 4
Create a Database Migration to Resize Image in CodeIgniter 4
We will store the image name in the database table. Hence, using the migration, you can generate a schema for the table.
php spark make:migration imageResize
The above command will create a migration file with the name timestamp_Imageresize.php.
After creating the migration file, let’s put the schema inside it.
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class Imageresize extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'auto_increment' => true
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '100'
],
'created_at datetime default current_timestamp',
'updated_at datetime default current_timestamp on update current_timestamp'
]);
$this->forge->addKey('id', true);
$this->forge->createTable('imageResize');
}
public function down()
{
$this->forge->dropTable('imageResize');
}
}
I have added the schema for the table. Now, this will need to be migrated inside the created database.
How to Send Email in CodeIgniter 4 Using Gmail SMTP
Migrate Table(s) in CodeIgniter 4
For migrating the table(s), you have to run the spark command in the terminal.
php spark migrate
This command will generate the table with the specified schema.
Create a Model To Resize Image in CodeIgniter 4
We needed a model to synchronize with the database. We already have the migration for a table. Hence, we can configure that table with a model. So, let’s create that then we will proceed further.
php spark make:model Image
After creating the model, paste the below code and make it look like same.
<?php
namespace App\Models;
use CodeIgniter\Model;
class Image extends Model
{
protected $DBGroup = 'default';
protected $table = 'images';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $protectFields = true;
protected $allowedFields = ['name'];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
}
In the next step, we will need a view. The view will contain a form with image upload input. Let’s create that.
Create a View For the Image Upload
You will find the Views folder inside the app folder. Now, create a view named image.php. After creating the view, let’s put the below code. In the below code, I have added a form element and inside that, there is an input type file. Also, there is a submit button.
<!doctype html>
<html lang="en">
<head>
<title>Codeigniter 4 Ajax Form Handling</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css">
<style>
.error {
color: #dc3545;
}
</style>
</head>
<body>
<?php $validation = \Config\Services::validation(); ?>
<div class="container py-4">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
<form method="POST" action="<?= base_url('image')?> " enctype="multipart/form-data">
<?= csrf_field() ?>
<?php
if(session()->getFlashdata('success')):?>
<div class="alert alert-success alert-dismissible">
<button type="button" class="btn-close" data-bs-dismiss="alert">×</button>
<?php echo session()->getFlashdata('success') ?>
</div>
<?php elseif(session()->getFlashdata('failed')):?>
<div class="alert alert-danger alert-dismissible">
<button type="button" class="btn-close" data-bs-dismiss="alert">×</button>
<?php echo session()->getFlashdata('failed') ?>
</div>
<?php endif; ?>
<div class="card shadow">
<div class="card-header">
<h5 class="card-title">Codeigniter 4 Image Upload and Resize</h5>
</div>
<div class="card-body p-4">
<div class="form-group mb-3 has-validation">
<label class="form-label" for="image">Image</label>
<input type="file" class="form-control <?php if($validation->getError('image')): ?>is-invalid<?php endif ?>" id="image" name="image" />
<?php if ($validation->getError('image')): ?>
<div class="invalid-feedback">
<?= $validation->getError('image') ?>
</div>
<?php endif; ?>
</div>
<button type="submit" id="submit-btn" class="btn btn-success">Save</button>
</div>
</div>
<?php
if(session()->getFlashdata('previewImage')):?>
<div class="form-group py-4">
<h5 class="py-2">Image Preview</h5>
<img src="<?php echo base_url('uploads/'.session()->getFlashdata('previewImage'));?>" class="img-fluid"/>
</div>
<?php endif; ?>
</form>
</div>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
</html>
For the form design, I have used Bootstrap 5. I have specified the form action. So, respectively, we have to define the routes. But, firstly, create a controller for implementing the functionality to resize image in CodeIgniter 4.
How to Implement jQuery Datatable in CodeIgniter 4
Create a Controller to Resize Image in Codeigniter 4
For creating the controller, I will use the spark command. Hence, open the terminal inside the project and hit the below command.
php spark make:controller ImageController
After creating the controller, you have to put the below snippet. Here, at the top, I have included the Model class (Image). In the constructor, I have called the CodeIgniter helper functions for form handling and URL redirection. Also, I have created the object of the Image model.
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\Image;
class ImageController extends BaseController
{
/**
* Constructor
*/
public function __construct()
{
helper(['form', 'url']);
$this->imageModel = new Image();
}
public function index()
{
return view('image');
}
/**
* Manipulate image and store
*/
public function store()
{
// image validation
$validated = $this->validate([
'image' => [
'uploaded[image]',
'mime_in[image,image/jpg,image/jpeg,image/gif,image/png]',
'max_size[image,4096]',
],
]);
if (!$validated) {
return view('image', [
'validation' => $this->validator
]);
}
$imagePath = $this->request->getFile('image');
$imageName = $imagePath->getRandomName();
// Image manipulation
$image = \Config\Services::image()
->withFile($imagePath)
->resize(240, 180, true, 'height')
->save(FCPATH . '/uploads/' . $imageName);
$imagePath->move(WRITEPATH . 'uploads');
$imageData = [
'name' => $imageName,
];
$result = $this->imageModel->save($imageData);
if ($result) {
session()->setFlashdata('success', 'Success! image uploaded.');
return redirect()->to(site_url('/image'))->withInput()->with('previewImage', $imageName);
} else {
session()->setFlashdata('failed', 'Failed! image not uploaded.');
return redirect()->to(site_url('/image'))->withInput()->with('previewImage', $imageName);
}
}
}
- Also, we have the index() function for loading the view. (We already created the view).
- In the store() function, we are handling the image validation. Also, we included the CodeIgniter service class that is
\Config\Services::image()
. - By using this service class, I have manipulated the actual image. Resized with a fixed dimension by giving an absolute width and height.
- You may find more detail about the \Config\Services::image().
That’s it for the functionality. In the next step, you have to create routes for rendering the view and getting results. So, let’s do that.
Generate Fake Data in CodeIgniter 4 Using Seeder and Faker
Create Routes
For creating the routes, navigate to the app/Config and Routes.php file. Now, add the below routes.
$routes->get('image', 'ImageController::index');
$routes->post('image', 'ImageController::store');
After adding the routes, let’s run the application to check the result.
Result For Image Resizing in CodeIgniter 4
Open the browser and hit the specified route in the URL. You will have the below form.
We have added the validation rules for the image. Hence, if you will try to submit the form without any proper image then it will throw the validation error message.
Let’s check the final result by uploading an image. Also, please check the dimension of that image to make sure the image is resized or not. After uploading the image, you will get the success response as shown below.
Now, for the confirmation, let’s navigate to the uploaded image and check the dimension.
In the result, you may see the image has been resized to the given height and width. By resizing the image you can reduce the image size also.
That’s it for this post.
Conclusion
We used CodeIgniter 4 service class to manipulate the image. By using this class, we resized image size by giving a fixed height and width. This class provides many other options for image manipulation. After resizing the image you can reduce the image size and it will enhance the speed and performance of your application. I hope you will find helpful to this post.
Leave a Reply