Categories
Android OpenCV Programming

Use OpenCV to show camera on android App with correct orientation

Return to OpenCV 4 Android Tutorials List

In this series of tutorials, you are learning OpenCV for Android using Android Studio. So far, you have made a working OpenCV Android Studio Project containing OpenCV module.

In Here is the overview of what we are going to achieve:

  • Create an OpenCV for Android Project (As in previous tutorial in this series) (Here)
  • Show Camera on the Screen
    1. Edit Manifest
      1. Add permission to allow camera.
      2. Support various screen sizes and adaptability of camera.
      3. Use specific features of the camera.
    2. Add a custom Layout show_camera.xml to display camera in it.
    3. Edit MainActivity_show_camera.java 
      1. Import required android classes
      2.  Import OpenCV classes
      3. Connect to OpenCV manager
      4. Initiate LogCat to log events of out app
      5. SHOW CAMERA ON LAYOUT
      6. Corrected Orientation (portrait)

Trust me, it is very simple to do. Lets do it!


 

Manifest.xml

We need to edit the AndroidManifest.xml file like following:

  1. Allow permission to use camera
    <uses-permission android:name="android.permission.CAMERA"/>
  2. Allow camera to optimize to the dimensions of the device in use
    <supports-screens android:resizeable="true"
            android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:anyDensity="true" />
  3. Use Front camera and autofocus of camera :S
     <uses-feature android:name="android.hardware.camera" android:required="false"/>
        <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
        <uses-feature android:name="android.hardware.camera.front" android:required="false"/>
        <uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>

The Manifest.xml file in its entirety is given here

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="opencv.codeonion.com.opencv_test">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        >
        <activity
            android:name=".MainActivity_show_camera"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <supports-screens   android:resizeable="true"
                        android:smallScreens="true"
                        android:normalScreens="true"
                        android:largeScreens="true"
                        android:anyDensity="true" />

    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-feature android:name="android.hardware.camera" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.front" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>

</manifest>

 

This entire process is given here:

Show camera on android App using OpenCV for Android - Edit Manifest

This is all you need to do in AndroidManifest.xml


Create a new layout (show_camera.xml )

Now in your project, do the following:

  1. Create a new layout called show_camera.xml
  2. Add the following code it to:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        xmlns:opencv="http://schemas.android.com/apk/res-auto"
        android:layout_height="match_parent">
    
        <org.opencv.android.JavaCameraView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:visibility="gone"
            android:id="@+id/show_camera_activity_java_surface_view"
            opencv:show_fps="true"
            opencv:camera_id="any" />
    
    </LinearLayout>

    Note that the JavaCameraView has the id of show_camera_activity_java_surface_view

This is given below:

 


MainActivity_show_camera.java

Import the following Android Classes in your MainActivity_show_camera:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.WindowManager;

Import the following OpenCV classes in your MainActivity_show_camera:

import org.opencv.android.JavaCameraView;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

Now, lets work with the MainActivity_show_camera Class 🙂 (Code in the end). I will explain every line of OpenCV code in detail.

  • Implement the OpenCV class CvCameraViewListener2 to allow OpenCV to communicate with android camera functionalities.
public class MainActivity extends AppCompatActivity implements CvCameraViewListener2 {
  • Declare the following items in the class
    // Used for logging success or failure messages
        private static final String TAG = "OCVSample::Activity";
    
        // Loads camera view of OpenCV for us to use. This lets us see using OpenCV
        private CameraBridgeViewBase mOpenCvCameraView;
    
        // Used in Camera selection from menu (when implemented)
        private boolean              mIsJavaCamera = true;
        private MenuItem             mItemSwitchCamera = null;
    
        // These variables are used (at the moment) to fix camera orientation from 270degree to 0degree
        Mat mRgba;
        Mat mRgbaF;
        Mat mRgbaT;
  • Now, lets call OpenCV manager to help our app communicate with android phone to make OpenCV work
    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
            @Override
            public void onManagerConnected(int status) {
                switch (status) {
                    case LoaderCallbackInterface.SUCCESS:
                    {
                        Log.i(TAG, "OpenCV loaded successfully");
                        mOpenCvCameraView.enableView();
                    } break;
                    default:
                    {
                        super.onManagerConnected(status);
                    } break;
                }
            }
        };
    • CameraBridgeViewBase mOpenCvCameraView
      This variable acts as a bridge between camera and OpenCV library.
    • BaseLoaderCallback mLoaderCallback = …..
      Well, once OpenCV library is loaded, you may want to perform some actions. For example, displaying a success or failure message.
  • Initiate the LogCat
    public MainActivity_show_camera() {
            Log.i(TAG, "Instantiated new " + this.getClass());
        }
  • Now, when the activity is created, display the OpenCV camera in the layout. show_camera.xml.
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            Log.i(TAG, "called onCreate");
            super.onCreate(savedInstanceState);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    
            setContentView(R.layout.show_camera);
    
            mOpenCvCameraView = (JavaCameraView) findViewById(R.id.show_camera_activity_java_surface_view);
    
            mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
    
            mOpenCvCameraView.setCvCameraViewListener(this);
        }
  •  The following three functions handle the events when the app is Paused, Resumed and Closed/Destroyed
    @Override
        public void onPause()
        {
            super.onPause();
            if (mOpenCvCameraView != null)
                mOpenCvCameraView.disableView();
        }
    
        @Override
        public void onResume()
        {
            super.onResume();
            if (!OpenCVLoader.initDebug()) {
                Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
                OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
            } else {
                Log.d(TAG, "OpenCV library found inside package. Using it!");
                mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
            }
        }
    
        public void onDestroy() {
            super.onDestroy();
            if (mOpenCvCameraView != null)
                mOpenCvCameraView.disableView();
        }
  • Now, we will do two main things:
    • Receive Image Data when the camera preview starts on your screen 😀
      public void onCameraViewStarted(int width, int height) {
      
              mRgba = new Mat(height, width, CvType.CV_8UC4);
              mRgbaF = new Mat(height, width, CvType.CV_8UC4);
              mRgbaT = new Mat(width, width, CvType.CV_8UC4);
          }
    • Destroy image data when you stop camera preview on your phone screen
      public void onCameraViewStopped() {
              mRgba.release();
          }
    • Now, this one is interesting! OpenCV orients the camera to left by 90 degrees. So if the app is in portrait more, camera will be in -90 or 270 degrees orientation. We fix that in the next and the most important function. There you go!
          public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
      
              // TODO Auto-generated method stub
              mRgba = inputFrame.rgba();
              // Rotate mRgba 90 degrees
              Core.transpose(mRgba, mRgbaT);
              Imgproc.resize(mRgbaT, mRgbaF, mRgbaF.size(), 0,0, 0);
              Core.flip(mRgbaF, mRgba, 1 );
      
              return mRgba; // This function must return
          }

The entire code is given below:

package opencv.codeonion.com.opencv_test;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.WindowManager;

import org.opencv.android.JavaCameraView;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

// OpenCV Classes

public class MainActivity_show_camera extends AppCompatActivity implements CvCameraViewListener2 {

    // Used for logging success or failure messages
    private static final String TAG = "OCVSample::Activity";

    // Loads camera view of OpenCV for us to use. This lets us see using OpenCV
    private CameraBridgeViewBase mOpenCvCameraView;

    // Used in Camera selection from menu (when implemented)
    private boolean              mIsJavaCamera = true;
    private MenuItem             mItemSwitchCamera = null;

    // These variables are used (at the moment) to fix camera orientation from 270degree to 0degree
    Mat mRgba;
    Mat mRgbaF;
    Mat mRgbaT;

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                {
                    Log.i(TAG, "OpenCV loaded successfully");
                    mOpenCvCameraView.enableView();
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };

    public MainActivity_show_camera() {
        Log.i(TAG, "Instantiated new " + this.getClass());
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "called onCreate");
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.show_camera);

        mOpenCvCameraView = (JavaCameraView) findViewById(R.id.show_camera_activity_java_surface_view);

        mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);

        mOpenCvCameraView.setCvCameraViewListener(this);
    }

    @Override
    public void onPause()
    {
        super.onPause();
        if (mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }

    @Override
    public void onResume()
    {
        super.onResume();
        if (!OpenCVLoader.initDebug()) {
            Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
        } else {
            Log.d(TAG, "OpenCV library found inside package. Using it!");
            mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        }
    }

    public void onDestroy() {
        super.onDestroy();
        if (mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }

    public void onCameraViewStarted(int width, int height) {

        mRgba = new Mat(height, width, CvType.CV_8UC4);
        mRgbaF = new Mat(height, width, CvType.CV_8UC4);
        mRgbaT = new Mat(width, width, CvType.CV_8UC4);
    }

    public void onCameraViewStopped() {
        mRgba.release();
    }

    public Mat onCameraFrame(CvCameraViewFrame inputFrame) {

        // TODO Auto-generated method stub
        mRgba = inputFrame.rgba();
        // Rotate mRgba 90 degrees
        Core.transpose(mRgba, mRgbaT);
        Imgproc.resize(mRgbaT, mRgbaF, mRgbaF.size(), 0,0, 0);
        Core.flip(mRgbaF, mRgba, 1 );

        return mRgba; // This function must return
    }
}

The entire process of editing MainActivity_show_camera.java is shown here:

Show camera on android App using OpenCV for Android - MainActivity_show_camera


Note: The camera disorientation problem is a bitch an issue not to be takien lightheartedly. Thanks for noting.

This concludes this tutorial, now that you have created a camera app, it is now time to continue this and perform more Computer Vision! In the next tutorial, I will draw a simple object on the screen. Be sure to check out the list of OpenCV for Android tutorials for latest tutorials.

Thanks for reading, and please share and comment if this helped and to share your ideas and opinions.

Return to OpenCV 4 Android Tutorials List

Categories
Codeigniter Programming

CodeIgniter 3 – Create your own Hello World with simple form and database!

In the previous tutorial, you you learnt how to remove the “index.php” from URL. Now, we are ready for the “Hello World!” complete with code

GOALS!

In this tutorial, we will learn CodeIgniter 3 MVC by making a Hello World! program, complete with database, introduction to CRUD operations, form, switching pages and code. We will cover a LOT in this tutorial and I am sure you will get a lot of knowledge about CodeIgniter 3. Check the following list to see what you will learn.

  1. Create a database to be used by Model
  2. Connect the database to the web application
  3. Create a custom model:
    • Model will use the Database
    • model will contain a “Hello World!” in a function as a return value for controller to use.
  4. Create two custom views:
    • We will Load views from controller.
    • Pass data to the views using controller.
    • Use data from controller in Views.
    • Make a form which will work along with Controller.
    • Call controller custom function.
    • Pages association (move from page to page)
  5. Create a controller that will:
    • Load the model.
    • Use model function in controller.
    • Receive input from model in controller.
    • Interact with database using model.
    • Pass data to views using data[] array.
    • Create custom controller function.
    • Load views.
    • Load view from a button in another view.
    • Use helper;
    • Use constructor.

As you can see, this is a seriously deep “Hello World!” tutorial. I am sure that you will learn a lot in the end. You will be prepared to learn more without having to worry about learning the basics. Lets get started!

BEGIN!


Creating the Database

1. Create a Database

We will create a database to be used for this tutorial.

  1. In XAMPP, go to localhost/phpmyadmin/
  2. Create a  database called “citutorial
  3. Create a table using this SQL query
    CREATE TABLE `citutorial`.`helloworldtable` ( `id` INT NOT NULL AUTO_INCREMENT , `message` VARCHAR(255) NOT NULL , PRIMARY KEY (`id`) ) ENGINE = InnoDB;
  4. Now make a simple “Hello World!” entry in the table so that the table has just a single entry of
    id = 1
    message = Hello World!

Eventually, your table should look like this,

 

2. Connect the Database

Go to the /application/config/database.php and modify the settings for the database citutorial. You need to input the database username, password and database name. By default, the username in XAMPP is “root” and password is empty i.e. “”. And the database name is “citutorial. So the settings are,

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

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'citutorial',
	'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
);

Creating the Model

Understanding the Model

We will now understand the model which will retrieve the “Hello World!” message from the database table we created in steps 1 & 2. First, I will show you what method I used and then you will get the entire model code.

For this tutorial, I have first selected the “table” in our database using this line of code.

// $this->db->from("NAME_OF_TABLE");
$query = $this->db->from("helloworldtable");

Then, I provided the criteria to find the “Hello World!” message from the table like this. Note that in the following line of code, “message” is the column name and “Hello World!” is the specific search keyword that is to be matched in order to retrieve the value.

//$this->db->where('TABLE_COLUMN_NAME', "SEARCH_KEYWORD");
$query = $this->db->where('message', "Hello World!");

Then, I checked if the query was successful and performed an action on the basis of the success or failure of the query like so.

if(!$query){
	echo "Failed to find the \"Hello World\" Entry<br>";
}else{
	echo "Successfully found the \"Hello World\" Entry<br>";
	return $this->db->get()->result();
}

Note that in the end, I simply returned the result of the query like this.

return $this->db->get()->result();

(Alternative approach)

Now, note that all of this could also have been done using the following model function (which I won’t use).

function return_helloworld_message(){
	$this->db->from("helloworldtable");
	$this->db->where('message', "Hello World!");
	return $this->db->get()->result();
}

3. Creating the model

Lets finally create the model file and add the code.

  1. Go to \application\models\1_hello_world\ and create a file called “Helloworld_model.php”.
  2. Double check that the file name starts with a capital letter since it is important in CI3.0+ versions.
  3. Now, open the file and add the following code to it.
    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Helloworld_model extends CI_Model {
    
    	public function __construct()
        {
                // Call the CI_Model constructor
                parent::__construct();
        }
    
        function return_helloworld_message(){
        	// From the given table,
        	$query = $this->db->from("helloworldtable");
    
        	// Find where the column "message" has a value called "Hello World!"
        	$query = $this->db->where('message', "Hello World!");
    
        	// Check if the query was successful
        	if(!$query){
        		echo "Failed to find the \"Hello World\" Entry
    ";
        	}else{
        		echo "Successfully found the \"Hello World\" Entry
    ";
        		return $this->db->get()->result();
        	}
        	// Then, return the value from Model to the calling controller
        }
    }
    

This completes the model to be used in this tutorial.  Next, we will prepare our views to receive the input.


 

Creating the Views

For this tutorial, we will make two views.

  1. First view will be used to request a “Hello World!” query.
  2. Second view will be used to show the output (either failure or success)

4.1 Creating a view to request for a “Hello World!” message

This view will show a page which will ask the user to press a button to perform a request. Here are some points to note:

Follow these steps to make the request view..

  1. Go to \application\views\1_hello_world\ and create a file called “request_a_helloworld_message.php”.
  2. Add the following code to it.
    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    ?>
    <?php 
    
         echo $buttonText;
         echo $pageTitle;
         echo $heading;
    ?>
    <form action="<?php echo base_url();?>1_hello_world/helloworld/requestModel" method="post">
    <?php echo $button_info; ?>
    <input type="submit" value="<?php echo $buttonText; ?>" />
    </form>

4.2 Creating a view to show result

Upon completion of the request, an output message will be generated. This could contain either the “Hello World!” or an error message informing us about the failure to find the “Hello World!” message in database table.

    1. Go to \application\views\1_hello_world\ and create a file called “resultDisplay.php”.
    2. Add the following code to it
      <?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
      <?php
            echo pageTitle;
            foreach ($modelData as $row) { 
                  echo $row--->message;
            }
      ?>
      <form action="&lt;?php echo base_url();?&gt;1_hello_world/helloworld/" method="post">
      	<input type="submit" value="<?php echo $buttonText; ?>" />
      	
      	<table>
      		<tr>
      			<td><?php echo $button_info; ?></td>
      		</tr>
      	</table>
      </form>

 

Creating the Controller

Now comes the really interesting component of CodeIgniter. The Controller! The controller will allow us to perform the following functions of the Hello World! tutorial application.

    1. Load the database to be used by the Model.
    2. Allow switching between two views with a button.
    3. Send data from controller and model to the view.
    4. Loading views.
    5. Calling model functions and passing its result into the view.

Now, lets first understand how I used the controller in this tutorial.

Understanding the Controller

In my controller. I have two functions which are,

    1. index() function which by default loads a request view.
    2. requestModel() function which is called by clicking a button in the “request_a_helloworld_message.php”  view.

 

index()

In this function, I am simply loading a view and passing data to it. The data is passed as an array like this,

$data['pageTitle'] = "Codeonion Tutorials!";
$data['heading'] = "Welcome to Hello World! Request page!";
$data['button_info'] = "Press the button to see the message from model.";
$data['buttonText'] = "Submit a Request to model";

The reason I have done it is to show you how it is possible to control the data you wish to show in view from the controller, instead of actually typing it into the view as simple HTML.

When loading views, it is possible to pass data to it. You can even load entire views into variables and pass them into the view.

$this->load->view('1_hello_world/request_a_helloworld_message', $data);

 

requestModel()

In this function, I am calling a model function and basically passing its result into the view.

I am calling a model and giving it a name of “helloworldmodel” like this,

$this->load->model('1_hello_world/Helloworld_model', 'helloworldmodel');

Afterwards, I have called a model function called “return_helloworld_message()” and stored its output in “$data[‘modelData’]” like this,

$data['modelData'] = $this->helloworldmodel->return_helloworld_message();

Finally, as before, I have loaded a view to show results and passed data to it like this.

$this->load->view('1_hello_world/resultDisplay', $data);

 

5. Creating the controller

Now, we will finally create a controller and put the code in it.

  1. Go to \application\controllers\1_hello_world\ and create a Helloworld.php” and make sure that the file name starts with a capital letter
  2. Copy the following code into the Helloworld.php controller.
    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Helloworld extends CI_Controller {
    	public function __construct()
            {
                parent::__construct();
                // Helpers and libraries called in constructor will be available
                // in every function of this Helloworld controller class
                $this->load->database();
                $this->load->helper("URL");
            }
    
    	public function index(){
    
    		// General strings stored in $data array
    		// These are to be displayed in the "request_a_helloworld_message" view
    		$data['pageTitle'] = "Codeonion Tutorials!";
    		$data['heading'] = "Welcome to Hello World! Request page!";
    		$data['button_info'] = "Press the button to see the message from model.";
    		$data['buttonText'] = "Submit a Request to model";
    
    		// And we pass the data into the view.
    		$this->load->view('1_hello_world/request_a_helloworld_message', $data);
    	}
    
    	public function requestModel(){
    
    		// General Variables just like in index() function of this controller
    		$data['pageTitle'] = "Codeonion Tutorials!";
    		$data['heading'] = "This is the result!";
    		$data['button_info'] = "Press the button to see the Hello World! message.";
    		$data['buttonText'] = "Back";
    
    		// We load the model
    		$this->load->model('1_hello_world/Helloworld_model', 'helloworldmodel');
    
    		// We store the result of modal function in $data array
    		$data['modelData'] = $this->helloworldmodel->return_helloworld_message();
    
    		// We pass $data array into the "resultDisplay" view
    		$this->load->view('1_hello_world/resultDisplay', $data);
    
    	}
    }

    Now, you are ready to test the application.


 

Testing the Hello World! application

  1. Go to your browser (chrome in my case) and go to the following address (or the correct address according to your own setup)
    http://localhost/tutorial/1_hello_world/helloworld
  2. You will see the following on the browser
  3. Press the “Submit a Request to model” button and you will go to the following link
    http://localhost/tutorial/1_hello_world/helloworld/requestModel
  4. At this point, you will be seeing this output,
  5. At this point, you can press back to start over.

You can now see that your application can retrieve data from database. This is it! the tutorial is complete!


Conclusion

You have learnt how to create a complete MVC application using CodeIgniter complete with the database. You now have the knowledge required to learn and develop more advanced web applications.

If you found my post helpful or have any questions, please leave a comment. [button link=”https://www.facebook.com/ubaaconsultants” type=”small” newwindow=”yes”] Facebook[/button] [button link=”https://twitter.com/Codeonion” type=”small” newwindow=”yes”] Twitter[/button]

If you think that there is something missing, or you would like me to add something or even, if you wish to request a tutorial, just let me know and I will make a tutorial just for you.

Back to CodeIgniter Tutorials

Categories
Codeigniter Uncategorized

Codeigniter 2.20 – Sending E-mail using codeigniter

Back to CodeIgniter Tutorials

In CodeIgniter, sending e-mail is a simple process. First the library is loaded. Then the user provides e-mail related data. Finally, the E-mail is sent. Here is how E-mail is sent using a Controller in CodeIgniter

  1. Load the E-mail library of CodeIgniter
    $this->load->library('email');
  2. Provide set of characters that are to be permitted in the E-mail address.
    $config['permitted_uri_chars'] = 'a-z 0-9~%.:_()@&\-!';
  3. Initialize the type of e-mail as html (options text or html)
    $this->email->initialize(array('mailtype' => 'html'));
  4. Provide Sender’s E-mail address
    $this->email->from('EMAIL ADDRESS OF SENDER', 'NAME OF SENDER');
  5. Provide Receiver’s E-mail Address
    $this->email->to($RECEIVER_EMAIL_ADDRESS);
  6. Provide BCC E-mail address
    $this->email->bcc('BCC_PERSON@codeonion.com');
  7. Provide Subject of the E-mail
    $this->email->subject('THIS STRING IS THE SUBJECT OF EMAIL');
  8. Provide Body of the E-mail.
    $this->email->message('Hello my E-mail Receiver. ');
  9. Send the E-mail!
    $this->email->send();

Following is the complete code of the above process.

$this->load->library('email');
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_()@&\-!';
$this->email->initialize(array('mailtype' => 'html'));
$this->email->from('EMAIL ADDRESS OF SENDER', 'NAME OF SENDER');
$this->email->to($RECEIVER_EMAIL_ADDRESS);
$this->email->bcc('BCC_PERSON@codeonion.com');
$this->email->subject('THIS STRING IS THE SUBJECT OF EMAIL');
$this->email->message('Hello my E-mail Receiver. ');
$this->email->send();

Let me know in comments if there is something that you would like to know. And do like an share.

Back to CodeIgniter Tutorials