Truemag

  • Categories
    • Tips And Tricks
    • Internet
    • PHP
    • Javascript
    • CSharp
    • SQL Server
    • Linux
  • Lastest Videos
  • Our Demos
  • About
  • Contact
  • Home
  • Write With Us
  • Job Request
Home PHP CodeIgniter Upload And ReSize Image Maintain Ratio

CodeIgniter Upload And ReSize Image Maintain Ratio

This is an example that uses PHP CodeIgniter framework to upload an image then resize uploaded image to a specified width x height and maintain aspect ratio.

We have 3 steps as below.

1. Create a CodeIgniter View handles upload form

Let’s create a file named upload_example.php in CodeIgniter views folder like this.

And note that the form has enctype=”multipart/form-data” and action to UploadExample/do_upload, we will create UploadExample controller and do_upload action in step #2.

views/upload_example.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Demo CodeIgniter Upload And ReSize Image Maintain Ratio - 4rapiddev.com</title>
</head>
<body>
 
<form method="post" enctype="multipart/form-data" action="<?php echo base_url();?>index.php/UploadExample/do_upload"><p>
Please choose a file from your computer then click <strong>Submit</strong> to see the result.<br>
We accept file extensions: gif, jpg and png, under 4MBs
</p>
<input type="file" name="userfile" id="userfile" size="20" /><br><br>
<button type="submit" class="btn btn-info">Submit</button>
</form>
 
</body>
</html>

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Demo CodeIgniter Upload And ReSize Image Maintain Ratio - 4rapiddev.com</title> </head> <body> <form method="post" enctype="multipart/form-data" action="<?php echo base_url();?>index.php/UploadExample/do_upload"> <p> Please choose a file from your computer then click <strong>Submit</strong> to see the result.<br> We accept file extensions: gif, jpg and png, under 4MBs </p> <input type="file" name="userfile" id="userfile" size="20" /><br><br> <button type="submit" class="btn btn-info">Submit</button> </form> </body> </html>

2. Create a CodeIgniter controller handles uploading and resizing image

Let’s create a file named UploadExample.php in CodeIgniter controllers folder like this.

controllers/UploadExample.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
class UploadExample extends CI_Controller {
 
	public function index()
	{
		$this->load->view('upload_example');
	}
 
	public function do_upload()
	{
		$data = array();
 
		$file_element_name = 'userfile';
 
		$user_upload_path = 'data/user_uploads/images/';
 
		$config['upload_path'] = './' . $user_upload_path;
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size']  = 1024 * 4;
		$config['encrypt_name'] = TRUE;
 
		$this->load->library('upload', $config);
 
		if (!$this->upload->do_upload($file_element_name))
		{
			$data['upload_error'] = $this->upload->display_errors();
		}
		else
		{
			$data_upload = $this->upload->data();
 
			$file_name = $data_upload["file_name"];
			$file_name_thumb = $data_upload['raw_name'].'_thumb' . $data_upload['file_ext'];
 
			$this->load->library('image_lib');
			$config_resize['image_library'] = 'gd2';	
			$config_resize['create_thumb'] = TRUE;
			$config_resize['maintain_ratio'] = TRUE;
			$config_resize['master_dim'] = 'height';
			$config_resize['quality'] = "100%";
			$config_resize['source_image'] = './' . $user_upload_path . $file_name;
 
			$config_resize['height'] = 64;
			$config_resize['width'] = 1;
			$this->image_lib->initialize($config_resize);
			$this->image_lib->resize();
 
			$data["file_name_url"] = base_url() . $user_upload_path . $file_name;
			$data["file_name_thumb_url"] = base_url() . $user_upload_path . $file_name_thumb;
		}
 
		$this->load->view('upload_example_result',$data);
	}
 
	public function __construct()
	{
		parent::__construct();
	}
}

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class UploadExample extends CI_Controller { public function index() { $this->load->view('upload_example'); } public function do_upload() { $data = array(); $file_element_name = 'userfile'; $user_upload_path = 'data/user_uploads/images/'; $config['upload_path'] = './' . $user_upload_path; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = 1024 * 4; $config['encrypt_name'] = TRUE; $this->load->library('upload', $config); if (!$this->upload->do_upload($file_element_name)) { $data['upload_error'] = $this->upload->display_errors(); } else { $data_upload = $this->upload->data(); $file_name = $data_upload["file_name"]; $file_name_thumb = $data_upload['raw_name'].'_thumb' . $data_upload['file_ext']; $this->load->library('image_lib'); $config_resize['image_library'] = 'gd2'; $config_resize['create_thumb'] = TRUE; $config_resize['maintain_ratio'] = TRUE; $config_resize['master_dim'] = 'height'; $config_resize['quality'] = "100%"; $config_resize['source_image'] = './' . $user_upload_path . $file_name; $config_resize['height'] = 64; $config_resize['width'] = 1; $this->image_lib->initialize($config_resize); $this->image_lib->resize(); $data["file_name_url"] = base_url() . $user_upload_path . $file_name; $data["file_name_thumb_url"] = base_url() . $user_upload_path . $file_name_thumb; } $this->load->view('upload_example_result',$data); } public function __construct() { parent::__construct(); } }

Notes:

  • 1. index function: load the view upload_example to display the upload form.
  • 2. do_upload function: save uploaded file to web server, resize the file and display result.
    • userfile: (line 14) is the file input name we created in the upload form.
    • user_upload_path: (line 16) is the location on web server to save uploaded files. It must be writable.
    • maintain_ratio = TRUE: (line 39) to maintain aspect ratio
    • master_dim = height: (line 40) the height is used as the hard value
    • height = 64 and width = 1: (line 44 & 45) resized image’s height is always 64px and maintain ratio.

3. Create another CodeIgniter View to display resized image

Let’s create a file named upload_example_result.php in CodeIgniter views folder like this.

This will be called in the UploadExample controller to display the resized image or errors in case we upload an unsupported extension or exceed file size limit instead.

views/upload_example_result.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Demo CodeIgniter Upload And ReSize Image Maintain Ratio - 4rapiddev.com</title>
</head>
<body>
<?php
	if(isset($upload_error))
		echo $upload_error;
	else
	{
?>
<p>
Please see the thumbnail and your orginal file.<br>
We will schedule to delete all upload files.<br>
<a href='http://4rapiddev.com' target='_blank'>4rapiddev.com</a>
</p>
<strong>Thumbnail:</strong>
<p><img src="<?php echo $file_name_thumb_url;?>" /></p>
 
<strong>Original:</strong>
<p><img src="<?php echo $file_name_url;?>" /></p>
<?php
	}
?>
</body>
</html>

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Demo CodeIgniter Upload And ReSize Image Maintain Ratio - 4rapiddev.com</title> </head> <body> <?php if(isset($upload_error)) echo $upload_error; else { ?> <p> Please see the thumbnail and your orginal file.<br> We will schedule to delete all upload files.<br> <a href='http://4rapiddev.com' target='_blank'>4rapiddev.com</a> </p> <strong>Thumbnail:</strong> <p><img src="<?php echo $file_name_thumb_url;?>" /></p> <strong>Original:</strong> <p><img src="<?php echo $file_name_url;?>" /></p> <?php } ?> </body> </html>

Oct 26, 2014Hoan Huynh

Demo page

Fatal error: Using $this when not in object contextRecord Screen On Macbook OS X Mavericks or OS X Mountain Lion
You Might Also Like:
  • Codeigniter Pagination Show Total Pages
  • CodeIgniter Send Email Via SMTP Charset UTF-8
  • Configure To Run Codeigniter In Sub Folder Or Sub Directory
  • CodeIgniter Save Or Log All MySQL Queries
  • CodeIgniter Get Current Controller Function/Action
  • ASP.NET Resize Image High Quality
  • PHP Get Image Width And Height
  • Resize picture by using Paint
  • Free Test Upload Speed And Download Speed Service
  • PHP Get Remote Image Width Height
Hoan Huynh

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at [email protected]

Link6 years ago PHPCodeigniter, CodeIgniter ReSize, CodeIgniter Upload, display_errors, image_lib, multipart/form-data2,384
0
GooglePlus
0
Facebook
0
Twitter
0
Digg
0
Delicious
0
Stumbleupon
0
Linkedin
0
Pinterest
Most Viewed
PHP Download Image Or File From URL
22,210 views
Notepad Plus Plus Compare Plugin
How To Install Compare Text Plugin In Notepad Plus Plus
20,080 views
Microsoft SQL Server 2008 Attach Remove Log
Delete, Shrink, Eliminate Transaction Log .LDF File
15,855 views
JQuery Allow only numeric characters or only alphabet characters in textbox
13,336 views
C# Read Json From URL And Parse/Deserialize Json
9,831 views
4 Rapid Development is a central page that is targeted at newbie and professional programmers, database administrators, system admin, web masters and bloggers.
Recent Posts
  • How To Write a Applying Letter
  • Photo Editor App – How Good Is it?

  • The Best Way To Write An Essay – Creating A Good Essay
  • Free Online Photo Editor
  • Easy Tips For Writing An Essay
Categories
  • CSharp (45)
  • Facebook Graph API (19)
  • Google API (7)
  • Internet (87)
  • iPhone XCode (8)
  • Javascript (35)
  • Linux (28)
  • MySQL (16)
  • PHP (84)
  • Problem Issue Error (29)
  • Resources (32)
  • SQL Server (25)
  • Timeline (5)
  • Tips And Tricks (141)
  • Uncategorized (115)
Recommended
  • Custom Software Development Company
  • Online Useful Tools
  • Premium Themes
  • VPS
2014 © 4 Rapid Development