Create Multiple Thumbnails at once in Codeigniter [SOLVED]

Create Multiple Thumbnails at once in Codeigniter [SOLVED]

Today I will share with you a VERY EFFECTIVE technique for increasing your site PageSpeed.

(Step-by-Step)

In fact, I managed to increase my site PageSpeed from 63% to 88%.

PageSpeed GTmetrix

Why?

Simple, I created multiple thumbnails size image when I post my article.

That way, I have several images with different sizes so that I can put the image the right size on the right page.

Consider the following picture for more details:

my blog post

In the picture above, it can be seen in the blog image, I displayed a large image (710x344px).

Whereas in the sidebar, I display a small image (140x68px).

Before I found this technique, I displayed a large image on the sidebar, because I only have one image. That original image (710x344px).

That's what makes my site PageSpeed score so bad.

So, how to create multiple thumbnails size images with CodeIgniter?

Let's get started.

 

Step #1. Preparation

This is important!

If you skip this step, that means you missed the whole of this tutorial.

Good preparation will determine the success of you following this tutorial.

Don't skip this step, even though it feels complex.

So, what do you need to prepare?

1. Codeigniter

Codeigniter is the main PHP framework that we will use in this tutorial. If you don't have it yet, please download it on the official site: www.codeigniter.com

2. Jquery

Jquery is a javascript library that serves to help us to make it easier to manipulate the HTML elements.

Because we will use bootstrap, so we need Jquery to make BOOTSTRAP running well.

If you don't have it yet, please download it on the official site: jquery.com

3. Bootstrap

Bootstrap is a framework that contains CSS and JavaScript files that help facilitate web developers in designing a good and responsive User Interface (UI).

If you don't have it yet, please download it on the official site: https://getbootstrap.com/

 

Step #2. Codeigniter Installation

Extract CodeIgniter which has been downloaded before to the www directory (if you use a WampServer) or htdocs (if you use a XAMPP).

Here I use the WampServer. So, I extract it in the directory c:/wamp/www/

And then, rename "CodeIgniter" to be "upload".

Pay attention to the following picture for more details:

Project name

Open the "upload" folder, then create a new folder named "assets" parallel to the application and system folder, then create the css, images, and js folders into the assets folder.

Pay attention to the following picture for more details:

Project Structure

After that copy the bootstrap.css file into the css folder and copy the jquery and bootstrap.js files to the js folder.

Pay attention to the following picture for more details:

css and js folder

After that create 3 new folders "large", "medium", and "small" into the images folder.

Like the following picture:

image folder

Large, medium and small folders are folders where the thumbnail image is saved later in accordance with the resolution.

 

Step #3. Codeigniter Configuration

Here are some files that you need to configure:

1. Autoload.php

To configure the autoload.php file, please open the folder:

application/config/autoload.php

Like the following picture:

autoload

Open autoload.php using a text editor or IDE such as Notepad ++, Atom, or Sublime Text.

And then find the following code:

$autoload['libraries'] = array();
$autoload['helper'] = array();

Change to be like this:

$autoload['libraries'] = array('session');
$autoload['helper'] = array('url');

2. Config.php

To configure the config.php file, please open the folder:

application/config/config.php

Like the following picture:

config

Open config.php using the text editor, then find the following code:

$config['base_url'] = '';

Change to be like this:

$config['base_url'] = 'http://localhost/upload/';

3.Routes.php

To configure the routes.php file, please open the folder:

application/config/routes.php

Like the following picture:

Routes

Open routes.php using the text editor, then find the following code:

$route['default_controller'] = 'welcome';

Change to be like this:

$route['default_controller'] = 'upload';

 

Step #4. Basic Upload Multiple Thumbnails

In this step, I will share about basic of upload multiple thumbnails with Codeigniter.

Multiple thumbnails are the result of uploading images of different sizes and resolutions.

In this case, I want to upload multiple thumbnails that produce three different image sizes.

That is: large(700 X 467 pixels), medium(600 X 400 pixels) and small(100 X 67 pixels).

However, the upload will be 4 images: large, medium, small, and original image.

Let’s get started.

Create a Controller file in the "application/controllers" folder named “Upload.php”, then type the following code:

<?php
class Upload extends CI_Controller{

  function __construct(){
    parent::__construct();
    $this->load->library('upload');
  }
  function index(){
    $this->load->view('upload_view');
  }

  function do_upload(){
      $config['upload_path'] = './assets/images/'; //path folder
	    $config['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
	    $config['encrypt_name'] = TRUE;

	    $this->upload->initialize($config);

      if(!empty($_FILES['filefoto']['name'])){
		        if ($this->upload->do_upload('filefoto')){
		            $gbr = $this->upload->data();
	              //Compress Image
                $this->_create_thumbs($gbr['file_name']);
                $this->session->set_flashdata('msg','<div class="alert alert-info">Image Upload Successful.</div>');
                redirect('upload');
				    }else{
		            echo $this->upload->display_errors();
		    	  }

		    }else{
				    echo "image is empty or type of image not allowed";
			}
  }

  function _create_thumbs($file_name){
        // Image resizing config
        $config = array(
            // Large Image
            array(
                'image_library' => 'GD2',
                'source_image'  => './assets/images/'.$file_name,
                'maintain_ratio'=> FALSE,
                'width'         => 700,
                'height'        => 467,
                'new_image'     => './assets/images/large/'.$file_name
                ),
            // Medium Image
            array(
                'image_library' => 'GD2',
                'source_image'  => './assets/images/'.$file_name,
                'maintain_ratio'=> FALSE,
                'width'         => 600,
                'height'        => 400,
                'new_image'     => './assets/images/medium/'.$file_name
                ),
            // Small Image
            array(
                'image_library' => 'GD2',
                'source_image'  => './assets/images/'.$file_name,
                'maintain_ratio'=> FALSE,
                'width'         => 100,
                'height'        => 67,
                'new_image'     => './assets/images/small/'.$file_name
            ));

        $this->load->library('image_lib', $config[0]);
        foreach ($config as $item){
            $this->image_lib->initialize($item);
            if(!$this->image_lib->resize()){
                return false;
            }
            $this->image_lib->clear();
        }
    }

}

In the Upload.php controller above, there are 4 functions. That is function __constract(), function index(), function do_upload(), and function _create_thumbs().

Function __construct() is a function as a constructor, which in this case is used to call the library upload. 

Function index() is a function to display a view that is “upload_view”.

Function do_upload() is a function to upload images to the server, and then creating multiple thumbnails by calling the function _create_thumbs().

Function _create_thumbs() is a function to create multiple thumbnails.

If you look carefully, there is an underscore ("_") in “function _create_thumbs()” at the beginning of the function name.

It means, the “function _create_thumbs()” cannot be called via a URL.

Next, create a view named “upload_view.php” on “application/views”.

Then type the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Multiple Thumbnails Codeigniter.</title>
    <link href="<?php echo base_url().'assets/css/bootstrap.css'?>" rel="stylesheet">
  </head>
  <body>
    <div class="container">
      <?php echo $this->session->flashdata('msg');?>
      <div class="row">
          <form class="form-horizontal" action="<?php echo site_url('upload/do_upload');?>" method="post" enctype="multipart/form-data">
            <div class="form-group">
              <label for="FormControlFile">File Image:</label>
              <input type="file" name="filefoto" class="form-control-file" id="FormControlFile" required>
            </div>
            <button type="submit" class="btn btn-primary">Upload</button>
          </form>
      </div>
    </div>
    <script src="<?php echo base_url().'assets/js/jquery-3.3.1.min.js'?>"></script>
    <script src="<?php echo base_url().'assets/js/bootstrap.js'?>"></script>
  </body>
</html>

Then open your browser and visit the following URL:

http://localhost/upload/

if running well, it will appear as shown below:

form upload

Then click “Browse…” to select the image that you want to upload.

browse image

Then click the "Upload" button to upload the image.

If the upload is successful, a message will appear as follows:

upload successful

Please check on the folder "assets/images" to make sure the upload is successful.

If successful, it will look like the following picture:

success uploaded

In the picture above, you can see there are 4 images in the “assets/images” folder.

In the "large" folder there is an image with a resolution of 700 x 467 pixels, in the "medium" folder there is an image with a resolution of 600 x 400 pixels, and in the folder "small" there is an image with a resolution of 100 x 67 pixels.

While the image outside the folder is an image with the original resolution.

 

Step #5. Create Multiple Thumbnails with Database

What if using a database?

I am sure that question comes in your mind.

In this step, I will share with you how to upload multiple sizes of thumbnails and insert the path of the images into the database.

Let’s dive right in.

 

#1. Create Database and Table Structure

Create a database on MySQL with the name “thumbs_db”.

To create a database “thumbs_db” on MySQL can be done by executing the following query:

CREATE DATABASE thumbs_db;

Next, create a table with the name “images” inside the “thumbs_db” database.

To create an "images" table on the database thumbs_db, it can be done by executing the following query:

CREATE TABLE images(
image_id INT PRIMARY KEY AUTO_INCREMENT,
image_title VARCHAR(100),
image_large VARCHAR(50),
image_medium VARCHAR(50),
image_small VARCHAR(50)
)ENGINE=INNODB;

The query above will create a table with the name "images" with fields: image_id, image_title, image_large, image_medium, and image_small.

 

#2. Connect to Database

To connect CodeIgniter to the database, it can be done by configuring the autoload.php and database.php files found in the “application/config” folder.

Open the autoload.php file in the “application/config” folder, and find the following code:

$autoload['libraries'] = array('session');

And set to be like this:

$autoload['libraries'] = array('session','database');

Next, open the database.php file found in the “application/config” folder and find the following code:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => '',
	'password' => '',
	'database' => '',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

And then set to be like this:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'thumbs_db',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

 

#3. Models

Create a model named “Upload_model.php” in the “application/models” folder.

Then type the following code:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Upload_model extends CI_Model{
    //show all images
    function show_images(){
        $query = $this->db->get('images');
        return $query;
    }

    //insert to database
    function insert_images($title,$image_large,$image_medium,$image_small){
      $data = array(
            'image_title'   => $title,
            'image_large'   => $image_large,
            'image_medium'  => $image_medium,
            'image_small'   => $image_small
      );
      $this->db->insert('images', $data);
    }

}

In the “Upload_model.php” model above there are two functions, namely: function show_images() and function insert_images().

The function show_images() is a function to retrieve image data from the database to display in the view.

While the function insert_images(), is a function to input data image path to the database.

 

#4. Controller

Reopen the Controller “Upload.php” that was created before, then change it to be like the code below:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Upload extends CI_Controller{

  function __construct(){
    parent::__construct();
    $this->load->library('upload');
    //load model Upload_model.php
    $this->load->model('Upload_model','upload_model');
  }

  function index(){
    $this->load->view('upload_view');
  }

  function do_upload(){
      $config['upload_path'] = './assets/images/'; //path folder
	    $config['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
	    $config['encrypt_name'] = TRUE;

	    $this->upload->initialize($config);

      if(!empty($_FILES['filefoto']['name'])){
		    if ($this->upload->do_upload('filefoto')){
		    $img = $this->upload->data();
	          //Compress Image
                $this->_create_thumbs($img['file_name']);

                $title = $this->input->post('title',TRUE);
                $image_large = $img['file_name'];
                $image_medium = $img['file_name'];
                $image_small = $img['file_name'];

                $this->upload_model->insert_images($title,$image_large,$image_medium,$image_small);
                $this->session->set_flashdata('msg','<div class="alert alert-info">Image Upload Successful.</div>');
                redirect('upload/show_images');
				    }else{
		            echo $this->upload->display_errors();
		    	  }

		    }else{
				    echo "image is empty or type of image not allowed";
			}
  }

  function _create_thumbs($file_name){
        // Image resizing config
        $config = array(
            // Large Image
            array(
                'image_library' => 'GD2',
                'source_image'  => './assets/images/'.$file_name,
                'maintain_ratio'=> FALSE,
                'width'         => 700,
                'height'        => 467,
                'new_image'     => './assets/images/large/'.$file_name
                ),
            // Medium Image
            array(
                'image_library' => 'GD2',
                'source_image'  => './assets/images/'.$file_name,
                'maintain_ratio'=> FALSE,
                'width'         => 600,
                'height'        => 400,
                'new_image'     => './assets/images/medium/'.$file_name
                ),
            // Small Image
            array(
                'image_library' => 'GD2',
                'source_image'  => './assets/images/'.$file_name,
                'maintain_ratio'=> FALSE,
                'width'         => 100,
                'height'        => 67,
                'new_image'     => './assets/images/small/'.$file_name
            ));

        $this->load->library('image_lib', $config[0]);
        foreach ($config as $item){
            $this->image_lib->initialize($item);
            if(!$this->image_lib->resize()){
                return false;
            }
            $this->image_lib->clear();
        }
    }

    //function to show images to view
    function show_images(){
      $data['images']=$this->upload_model->show_images();
      $this->load->view('images_view', $data);
    }

}

 

#5. Views

Reopen View Upload_view.php that was created before, then change it to be like the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Multiple Thumbnails Codeigniter.</title>
    <link href="<?php echo base_url().'assets/css/bootstrap.css'?>" rel="stylesheet">
  </head>
  <body>
    <div class="container">
      
      <div class="row">
          <form class="form-horizontal" action="<?php echo site_url('upload/do_upload');?>" method="post" enctype="multipart/form-data">

            <div class="form-group">
              <label for="FormControlTitle">Title:</label>
              <input type="text" name="title" class="form-control" id="FormControlTitle" required>
            </div>

            <div class="form-group">
              <label for="FormControlFile">File Image:</label>
              <input type="file" name="filefoto" class="form-control-file" id="FormControlFile" required>
            </div>

            <button type="submit" class="btn btn-primary">Upload</button>
          </form>
      </div>

    </div>
    <script src="<?php echo base_url().'assets/js/jquery-3.3.1.min.js'?>"></script>
    <script src="<?php echo base_url().'assets/js/bootstrap.js'?>"></script>
  </body>
</html>

After that create one more view with the name "images_view.php" in the “application/views” folder.

Then type the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Multiple Thumbnails Codeigniter.</title>
    <link href="<?php echo base_url().'assets/css/bootstrap.css'?>" rel="stylesheet">
  </head>
  <body>
    <div class="container-fluid">
      <?php echo $this->session->flashdata('msg');?>

      <div class="row">
          <table class="table">
            <thead>
              <tr>
                <th>Title</th>
                <th>Image Large</th>
                <th>Image Medium</th>
                <th>Image Small</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach($images->result() as $row):?>
                <tr>
                  <td><?php echo $row->image_title;?></td>
                  <td><img src="<?php echo base_url().'assets/images/large/'.$row->image_large;?>"></td>
                  <td><img src="<?php echo base_url().'assets/images/medium/'.$row->image_medium;?>"></td>
                  <td><img src="<?php echo base_url().'assets/images/small/'.$row->image_small;?>"></td>
                </tr>
              <?php endforeach;?>
            </tbody>
          </table>
      </div>

    </div>
    <script src="<?php echo base_url().'assets/js/jquery-3.3.1.min.js'?>"></script>
    <script src="<?php echo base_url().'assets/js/bootstrap.js'?>"></script>
  </body>
</html>

View "images_view.php" is a view to display all the images from the database in the form of a table.

 

#6. Testing

Open your browser, then visit the following URL:

http://localhost/upload/

Then it will appear as shown below:

upload form

Input Title and Browse for the image you want to upload.

Like the following picture:

browse image

Click the "Upload" button to upload the image.

If the upload is successful, it will appear as shown below:

show all images

In the picture above, you can see the difference of the resolution between large, medium and small images.

So, you can place the image on your website according to the resolution.

 

Conclusion:

This discussion is about how to create upload multiple sizes of thumbnails with CodeIgniter.

Where an uploaded image can be made into several different sizes and resolutions.

So, you can display the image on your website according to the resolution.

The goal is to optimize your site PageSpeed.

PageSpeed can boost User Experience (UX) and SEO Friendly.

So, how high the PageSpeed score you want?

Download Source

Share:



Sponsorship:



Comments (0)

Leave a Comment