Sunteți pe pagina 1din 31

Create Multiple Thumbnails at

once in Codeigniter [SOLVED]


 FEBRUARY 25, 2019

 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:


 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:


 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 assetsfolder.

 Pay attention to the following picture for more details:

 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:

 After that create 3 new folders "large", "medium", and "small" into

the images folder.


 Like the following picture:

 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:


 Open autoload.php using a text editor or IDE such as Notepad

++, Atom, or Sublime Text.

 And then find the following code:

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

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

 Change to be like this:

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

2 $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:


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

1 $config['base_url'] = '';

 Change to be like this:

1 $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:


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

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

 Change to be like this:

1 $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:

1 <?php

class Upload extends CI_Controller{


2

3
function __construct(){
4
parent::__construct();
5
$this->load->library('upload');
6
}
7
function index(){
8 $this->load->view('upload_view');
9 }

10
11 function do_upload(){

12 $config['upload_path'] = './assets/images/'; //path folder

$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
13
$config['encrypt_name'] = TRUE;
14

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

17
if(!empty($_FILES['filefoto']['name'])){
18
if ($this->upload->do_upload('filefoto')){
19 $gbr = $this->upload->data();
20 //Compress Image
21 $this->_create_thumbs($gbr['file_name']);

22 $this->session->set_flashdata('msg','<div class="alert alert-info">


Successful.</div>');
23
redirect('upload');
24
}else{
25 echo $this->upload->display_errors();
26 }

27

28 }else{

29 echo "image is empty or type of image not allowed";

}
30
}
31

32
function _create_thumbs($file_name){
33
// Image resizing config
34
$config = array(
35 // Large Image
36 array(
37 'image_library' => 'GD2',

38 'source_image' => './assets/images/'.$file_name,

39 'maintain_ratio'=> FALSE,

40 'width' => 700,

41 'height' => 467,


42 'new_image' => './assets/images/large/'.$file_name

43 ),

44 // Medium Image

array(
45
'image_library' => 'GD2',
46
'source_image' => './assets/images/'.$file_name,
47
'maintain_ratio'=> FALSE,
48
'width' => 600,
49
'height' => 400,
50
'new_image' => './assets/images/medium/'.$file_name
51
),
52
// Small Image
53 array(
54 'image_library' => 'GD2',
55 'source_image' => './assets/images/'.$file_name,

56 'maintain_ratio'=> FALSE,

57 'width' => 100,

58 'height' => 67,

59 'new_image' => './assets/images/small/'.$file_name

60 ));

61

62 $this->load->library('image_lib', $config[0]);

foreach ($config as $item){


63
$this->image_lib->initialize($item);
64
if(!$this->image_lib->resize()){
65
return false;
66
}
67 $this->image_lib->clear();
68 }
69 }

70

71 }

72
73

74

75

76

 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:

2 <!DOCTYPE html>

<html lang="en">
3
<head>
4
<meta charset="utf-8">
5
<title>Multiple Thumbnails Codeigniter.</title>
6
<link href="<?php echo base_url().'assets/css/bootstrap.css'?>" rel="stylesheet
7
</head>
8 <body>
9 <div class="container">

10 <?php echo $this->session->flashdata('msg');?>

11 <div class="row">

<form class="form-horizontal" action="<?php echo site_url('upload/do_uploa


12
data">
13 <div class="form-group">
14 <label for="FormControlFile">File Image:</label>

15 <input type="file" name="filefoto" class="form-control-file" id="FormCo

16 </div>

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

</form>
18
</div>
19
</div>
20
<script src="<?php echo base_url().'assets/js/jquery-3.3.1.min.js'?>"></script>
21
<script src="<?php echo base_url().'assets/js/bootstrap.js'?>"></script>
22 </body>
23 </html>

24

 Then open your browser and visit the following URL:


1 http://localhost/upload/

 if running well, it will appear as shown below:

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

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

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


 Please check on the folder "assets/images" to make sure the

upload is successful.

 If successful, it will look like the following picture:

 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:

1 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:

1
CREATE TABLE images(
2 image_id INT PRIMARY KEY AUTO_INCREMENT,
3 image_title VARCHAR(100),

4 image_large VARCHAR(50),

5 image_medium VARCHAR(50),

image_small VARCHAR(50)
6
)ENGINE=INNODB;
7

 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.phpand database.php files found in the

“application/config” folder.

 Open the autoload.php file in the “application/config” folder, and

find the following code:

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

 And set to be like this:

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

 Next, open the database.php file found in

the “application/config” folder and find the following code:

1 $active_group = 'default';

2 $query_builder = TRUE;

4 $db['default'] = array(

5 'dsn' => '',

'hostname' => 'localhost',


6
'username' => '',
7
'password' => '',
8
'database' => '',
9
'dbdriver' => 'mysqli',
10
'dbprefix' => '',
11 'pconnect' => FALSE,
12 'db_debug' => (ENVIRONMENT !== 'production'),

13 'cache_on' => FALSE,

14 'cachedir' => '',


15 'char_set' => 'utf8',

16 'dbcollat' => 'utf8_general_ci',

'swap_pre' => '',


17
'encrypt' => FALSE,
18
'compress' => FALSE,
19
'stricton' => FALSE,
20
'failover' => array(),
21 'save_queries' => TRUE
22 );

23

24

 And then set to be like this:

1 $active_group = 'default';

$query_builder = TRUE;
2

3
$db['default'] = array(
4
'dsn' => '',
5
'hostname' => 'localhost',
6
'username' => 'root',
7
'password' => '',
8 'database' => 'thumbs_db',
9 'dbdriver' => 'mysqli',
10 'dbprefix' => '',

11 'pconnect' => FALSE,

12 'db_debug' => (ENVIRONMENT !== 'production'),

'cache_on' => FALSE,


13
'cachedir' => '',
14
'char_set' => 'utf8',
15
'dbcollat' => 'utf8_general_ci',
16
'swap_pre' => '',
17 'encrypt' => FALSE,
18 'compress' => FALSE,
19 'stricton' => FALSE,

20 'failover' => array(),

'save_queries' => TRUE


21
);
22

23

24

 #3. Models

 Create a model named “Upload_model.php” in

the “application/models” folder.

 Then type the following code:

1 <?php

2 defined('BASEPATH') OR exit('No direct script access allowed');

3
class Upload_model extends CI_Model{
4
//show all images
5
function show_images(){
6
$query = $this->db->get('images');
7
return $query;
8
}
9

10 //insert to database
11 function insert_images($title,$image_large,$image_medium,$image_small){

12 $data = array(

13 'image_title' => $title,

14 'image_large' => $image_large,


15 'image_medium' => $image_medium,

16 'image_small' => $image_small

17 );

18 $this->db->insert('images', $data);

}
19

20
}
21

22

 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:

1 <?php

2 defined('BASEPATH') OR exit('No direct script access allowed');

3
4 class Upload extends CI_Controller{

6 function __construct(){

parent::__construct();
7
$this->load->library('upload');
8
//load model Upload_model.php
9
$this->load->model('Upload_model','upload_model');
10
}
11

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

15

16 function do_upload(){

17 $config['upload_path'] = './assets/images/'; //path folder

$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
18
$config['encrypt_name'] = TRUE;
19

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

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

26 $this->_create_thumbs($img['file_name']);

27

28 $title = $this->input->post('title',TRUE);

29 $image_large = $img['file_name'];

$image_medium = $img['file_name'];
30
$image_small = $img['file_name'];
31

32
$this->upload_model->insert_images($title,$image_large,$image_mediu
33
$this->session->set_flashdata('msg','<div class="alert alert-info">
34 Successful.</div>');
35 redirect('upload/show_images');

36 }else{

echo $this->upload->display_errors();
37
}
38

39
}else{
40
echo "image is empty or type of image not allowed";
41
}
42 }
43

44 function _create_thumbs($file_name){
45 // Image resizing config

46 $config = array(

47 // Large Image

array(
48
'image_library' => 'GD2',
49
'source_image' => './assets/images/'.$file_name,
50
'maintain_ratio'=> FALSE,
51
'width' => 700,
52
'height' => 467,
53
'new_image' => './assets/images/large/'.$file_name
54
),
55
// Medium Image
56 array(
57 'image_library' => 'GD2',

58 'source_image' => './assets/images/'.$file_name,

59 'maintain_ratio'=> FALSE,

60 'width' => 600,

61 'height' => 400,

62 'new_image' => './assets/images/medium/'.$file_name

63 ),

64 // Small Image

array(
65
66 'image_library' => 'GD2',

67 'source_image' => './assets/images/'.$file_name,

68 'maintain_ratio'=> FALSE,

69 'width' => 100,

70 'height' => 67,

71 'new_image' => './assets/images/small/'.$file_name

));
72

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

80 }

81 }

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

88 }
89

90

91

92

93

94


 #5. Views

 Reopen View Upload_view.php that was created before, then

change it to be like the following code:

1
<!DOCTYPE html>
2 <html lang="en">
3 <head>

4 <meta charset="utf-8">

5 <title>Multiple Thumbnails Codeigniter.</title>

<link href="<?php echo base_url().'assets/css/bootstrap.css'?>" rel="stylesheet


6
</head>
7
<body>
8
<div class="container">
9

10
<div class="row">
11
<form class="form-horizontal" action="<?php echo site_url('upload/do_uploa
12 data">

13
<div class="form-group">
14
<label for="FormControlTitle">Title:</label>
15
<input type="text" name="title" class="form-control" id="FormControlTit
16
</div>
17

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

21 </div>

22

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

24 </form>

</div>
25
26

27 </div>

28 <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>


29
</body>
30
</html>
31

32

 After that create one more view with the

name "images_view.php" in the “application/views”folder.

 Then type the following code:

1
<!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">

5 <title>Multiple Thumbnails Codeigniter.</title>

6 <link href="<?php echo base_url().'assets/css/bootstrap.css'?>" rel="stylesheet

</head>
7
<body>
8
<div class="container-fluid">
9
<?php echo $this->session->flashdata('msg');?>
10

11
<div class="row">
12 <table class="table">
13 <thead>
14 <tr>

15 <th>Title</th>

16 <th>Image Large</th>

<th>Image Medium</th>
17
<th>Image Small</th>
18
19 </tr>

20 </thead>

<tbody>
21
<?php foreach($images->result() as $row):?>
22
<tr>
23
<td><?php echo $row->image_title;?></td>
24
<td><img src="<?php echo base_url().'assets/images/large/'.$row->
25 <td><img src="<?php echo base_url().'assets/images/medium/'.$row-
26 <td><img src="<?php echo base_url().'assets/images/small/'.$row->

27 </tr>

28 <?php endforeach;?>

29 </tbody>

</table>
30
</div>
31

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

37

38

39

 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:


1 http://localhost/upload/

 Then it will appear as shown below:

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

 Like the following picture:


 Click the "Upload" button to upload the image.

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

 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.

S-ar putea să vă placă și