In this tutorial, we will learn how to resize an image before uploading it in Codeigniter 4. We will use the Codeigniter Image Library to resize the image before uploading it to the server.
The Codeigniter Image Library provides a simple way to resize images. It allows you to resize an image to a specific width and height, or to a percentage of its original size. You can also specify the quality of the resized image.
Let’s get started.
Step 1: Create a Controller
First, we need to create a controller to handle the image upload. Create a file called ImageController.php in the app/Controllers directory and add the following code:
” method=”post” enctype=”multipart/form-data”>
Step 3: Resize the Image
Now, we can add the code to resize the image before uploading it. Add the following code to the upload() method in the ImageController.php file:
public function upload() { // Get the file $file = $this->request->getFile(‘image’); // Resize the image $resizedImage = $file->resize(200, 200); // Save the resized image $resizedImage->save(‘uploads/resized.jpg’); // Upload the file $file->move(‘uploads’); }
In the code above, we are using the resize() method of the Codeigniter Image Library to resize the image to a width of 200px and a height of 200px. We are then saving the resized image to the uploads directory. Finally, we are uploading the original image to the uploads directory.
And that’s it! We have successfully resized an image before uploading it in Codeigniter 4.
To compress, resize, and manipulate image size in ci 4. In this tutorial, you will learn how to compress, resize and manipulate image size before uploading to the database and directories in Codeigniter 4 projects.
Codeigniter 4 Resize Image Before Upload Tutorial
By using the following steps, you can easily resize and compress image size before upload in codeigniter 4 projects:
- Step 1: Setup Codeigniter Project
- Step 2: Basic Configurations
- Step 3: Create Database With Table
- Step 4: Setup Database Credentials
- Step 5: Create Image Resize Controller
- Step 6: Create Image Upload Form View
- Step 7: Start Development server
Step 1: Setup Codeigniter Project
In this step, you will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”
Step 2: Basic Configurations
Next, you will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.
Set Base URL like this
public $baseURL = 'http://localhost:8080'; To public $baseURL = 'http://localhost/demo/';
Step 3: Create Database With Table
In this step, you need to create a database name demo, so open PHPMyAdmin and create the database with the name demo. After successfully create a database, you can use the below SQL query for creating a crop_images table in your database.
CREATE TABLE files(
id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
name varchar(100) NOT NULL COMMENT 'Name',
type varchar(255) NOT NULL COMMENT 'File Type',
created_at varchar(20) NOT NULL COMMENT 'Created date',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='demo table' AUTO_INCREMENT=1;
Step 4: Setup Database Credentials
In this step, you need to connect our project to the database. So, visit app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, YOU need to set up database credentials in this file like below.
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'demo',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'cacheOn' => false,
'cacheDir' => '',
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
Step 5: Create Image Resize Controller
In this step, Go to app/Controllers and create a controller name ImageUploadController.php. Then add the following code into it:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class ImageUploadController extends Controller {
public function index() {
return view('imageUploadForm');
}
public function upload() {
helper(['form', 'url']);
// access database
$database = \Config\Database::connect();
$db = $database->table('files');
// file validation
$isValidFile = $this->validate([
'file' => [
'uploaded[file]',
'mime_in[file,image/jpg,image/jpeg,image/png,image/gif]',
'max_size[file,4096]',
]
]);
// check validation
if (!$isValidFile) {
print_r('Upload valid file upto 4mb size');
} else {
$imgPath = $this->request->getFile('file');
// Image manipulation
$image = \Config\Services::image()
->withFile($imgPath)
->resize(200, 100, true, 'height')
->save(FCPATH .'/images/'. $imgPath->getRandomName());
$imgPath->move(WRITEPATH . 'uploads');
$fileData = [
'name' => $imgPath->getName(),
'type' => $imgPath->getClientMimeType()
];
$store = $db->insert($fileData);
print_r('Image has been successfully resized');
}
}
} ?>
Step 6: Create Image Upload Form View
In this step, you need to create imageUploadForm.php, go to application/views/ directory and create imageUploadFormphp file. and update the following HTML into your files:
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter Compress Image Size Example - Tutsmake.com</title>
</head>
<body>
<?php echo $error;?>
<form method='post' action='/ImageUploadController/upload' enctype='multipart/form-data'>
<input type="file" name="file" size="20" />
<input type="submit" value="upload" />
</form>
</body>
</html>
Step 7: Start Development server
For start development server, open your terminal and execute the following command it:
php spark serve
Then, Go to the browser and hit below the URL:
http://localhost:8080
Conclusion
Codeigniter compress, resize image size. In this tutorial, you have learned how to upload and compress, resize image size in CodeIgniter 4 app.
Recommended CodeIgniter Tutorials
If you have any questions or thoughts to share, use the comment form below to reach us.