file upload with resize image using codeigniter – onlinecode

file upload with resize image using codeigniter – onlinecode

In this post we will give you information about file upload with resize image using codeigniter – onlinecode. Hear we will give you detail about file upload with resize image using codeigniter – onlinecodeAnd how to use it also give you demo for it if it is necessary.

In this tutorial, we are going to how to generate a thumb image or resize an image using Codeigniter. Codeigniter is a PHP framework and it provides image library such as resize, rotate, crop and watermark. you can keep validation on image upload like as size and file type.

Here, we will use the GD2 library for the resize image using Codeigniter.

Creating a Project Directory

First, we have to need the 7.2+ PHP version and Apache 2.4 . after the download latest version of CodeIgniter and set up the project on the htdocs root directory. we will also create “assets/upload/product” and “assets/upload/product/thumb” directory on the project directory for the file upload.

Autoload Configuration

we will use the database, file upload, file validation, HTML in this project application. so we will configuration in the autoload.php. see below some load helpers and library in the autoload.php

PHP
$autoload['helper'] = array('html','url', 'file');
$autoload['libraries'] = array('database','form_validation');

Creating Controller Class

we will create the Resizeimage.php file in the “application/controllers” directory. first we will load the comman_model model in the constructor and after then we will crate index() and add() method.

When you the call index() method then it loads the view file and after submit the form then call the add() method.

simply we use below library load in the add() method for the file upload.

PHP
$this->load->library('upload', $config);

but, if you want to need to resize image then load the below library in the add() method.

PHP
$this->load->library('image_lib',$config); 
$this->image_lib->resize();

so. you can see below source code for resizing image.

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


class Resizeimage extends CI_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->model('common_model');
	}
	public function index()
	{
		$arrData['middle'] = 'product/add';
		$this->load->view('template',$arrData);
	}
 
	/**
	* add
	*
	* This help to add slider
	* 
	* @author	Nilesh dabhi
	* @access	public
	* @return	void
	*/
	
	public function add()
	{
		 if(isset($_POST['btnProduct']))
         {
                if ($_FILES['productImage']['name'] != '')
                {
					//echo "dfdf"; die;
                    //$config['upload_path'] = $_SERVER['DOCUMENT_ROOT'].'/assets/upload/product/';
					$config['upload_path'] = './assets/upload/product/';
                    $config['allowed_types'] = 'gif|jpg|png|jpeg';
                    $config['max_size'] = '10240';
					$ext = pathinfo($_FILES['productImage']['name'], PATHINFO_EXTENSION);
					$image = 'onlinecode' . '_' . rand(10000, 100000) . '.' . $ext;
					$config['file_name'] = $image;

                
                    $this->load->library('upload', $config);
                    if (!$this->upload->do_upload('productImage'))
                    {
                        // case - failure
                        $upload_error = array('error' => $this->upload->display_errors());
                        print_r($upload_error); die;
                    }
                    else
                    {
                        $inData["product_image"] = $this->upload->file_name;
                        $data = $this->upload->data();
                        $upload_data = $this->upload->data();

                        $config = array(
                            'source_image'     => $data['full_path'], //get original image
                            'new_image'        => $data['file_path'].'thumb', //save as new image //need to create thumbs first
                            'maintain_ratio'   => true,
                            'width'            => 150
                        );
                        //print_r($config); die;
                    

                        $this->load->library('image_lib',$config); //load library
                        $this->image_lib->resize(); //do whatever specified in config

                    }//end do-upload condition
                }//end productImage empty condition
				$inData["product_title"] = $_POST['txtProductTitle'];
                $inData["product_created"] = date('Y-m-d H:i:s');

                $insertFlag	= $this->common_model->insert('product',$inData);
				if($insertFlag)
				{
					$this->session->set_flashdata('success', 'Prodcut Added Successfully !!');
						redirect('resizeimage');
				}
				else
				{
					$this->session->set_flashdata('error', 'Failed to Add Product !!');
					redirect('product/add');
				}
        }
        $arrData['middle'] = 'product/add';
        $this->load->view('template', $arrData);
	}

}

Creating  Model

here, we will create a common_modal.php in the application/models/common_modal.php.

PHP
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Common_model extends CI_Model
{
	
	public function __construct()
	{
		$this->load->database('default');
			
		// Call the Model constructor
		parent::__construct();
	}
	public function insert($table,$arrData)
	{
		  if ($this->db->insert($table, $arrData)) 
		  {
            return true;
          } else 
		  {
            return false;
          }
	}
}
?>

Creating View Files

here, first, we will create the template.php file in the “application/views/” directory and add bootstrap in that file.

After then we will create an add.php file in the “application/views/product” directory, make the form with a file field and that file we pass as the middle for the template file.

 

template.php

PHP
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Codeigniter file upload with resize image</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="shortcut icon" href="//assets/front/images/expertxp_icon.ico">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
		<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
		<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>		
		<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
</head>
<body>
<div >
    <div >
      <div >
        <?php
          if ($this->session->flashdata('success')){
              ?>
              <div >
                  <!-- a title="Hide Notification"  href="#">x</a -->
                  <a href="#"  data-dismiss="alert" aria-label="close">&times;</a>
                  <h4>Success</h4>
                  <?php echo $this->session->flashdata('success') ?></p>
              </div>
              <?php
          }
          ?>
          <?php
          if ($this->session->flashdata('error')){
              ?>
              <div >
                  <!-- a title="Hide Notification"  href="#">x</a -->
                  <a href="#"  data-dismiss="alert" aria-label="close">&times;</a>
                  <h4>Error</h4>
                  <?php echo $this->session->flashdata('error') ?></p>
              </div>
              <?php
          }
          ?>
      </div>
    </div>
    <?php $this->load->view($middle);?>
</div>    
</body>
</html>

add.php

PHP
<div  style="margin-bottom:10px;">
        <div ><h2>codeigniter file upload with resize image</h2></div>
</div>
<form method="post" name="frmAdd" action="<?php echo base_url('resizeimage/add'); ?>" enctype="multipart/form-data">
  <div >
    <label for="txtProductTitle">Product Title:</label>
    <input type="text"  name="txtProductTitle" required  id="txtProductTitle">
  </div>
  
  <div >
    <label for="productImage">Product Image:</label>
    <input type="file"  required name="productImage" id="productImage" accept="image/*">
  </div>
  <input type="submit"  name="btnProduct" value="Add"/>
</form>

Configuring Route

We will change the default controller as Resizeimage in the application/config/routes.php

PHP
$route['default_controller'] = 'resizeimage';

You can download our source code

Please follow and like us:

Hope this code and post will helped you for implement file upload with resize image using codeigniter – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

18  +    =  23

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US