A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Code Igniter: Resize image and save to database; Generate thumbnails

Probably my first Code Igniter tutorial. This one shows you how you can save an image to a database. But before saving that image to a blob field, the image is re-sized first. This behavior is similar to Friendster’s image upload.

The Model

< ?php
class Photos_model extends Model
{
    private $_table = 'photos';
 
    public function __construct()
    {
        parent::Model();
        $this->db = $this->load->database('default', true);
    }
 
    public function upload_photo($data)
    {
        $this->db->insert($this->_table,$data);
    }
 
    public function update_photo($data,$listing_id)
    {
        $sql = "SELECT * FROM ".$this->_table." WHERE listing_id=".$listing_id;
        $result = $this->db->query($sql);
 
        if ($result->num_rows()) {
            $this->db->update($this->_table,$data,"listing_id=".$listing_id);
        } else {
            $data['listing_id']=$listing_id;
            $this->db->insert($this->_table,$data);
        }
 
    }
 
    /**
     * Fetch a photo from a Blob field
     *
     * @param unknown_type $condition
     * @return unknown
     */
    public function fetch_photo($condition)
    {
        $sql = "SELECT * FROM ".$this->_table." WHERE ".$condition."";
        if ($result = $this->db->query($sql)) {
            return $result->row_array();
        } else {
            return false;
        }
 
    }
 
    public function delete_photo($listing_id)
    {
        $sql = "DELETE FROM ".$this->_table." WHERE listing_id = ".$listing_id;
        if ($result = $this->db->query($sql)) {
            return true;
        } else {
            return false;
        }
    }
}

The Controllers
The Listing Controller: this controller saves the image to the database.

< ?php
 
class Listing extends Controller {
 
    private $_default_listing_status = 'pending';
 
	function Lisintg()
	{
		parent::Controller();	
	}
 
	/**
	 * shows the listing
	 *
	 */
	function index($id)
	{
	    $this->load->model('listing_model');
	    $data['item'] = $this->listing_model->get_item($id);
 
	    $headdata = array();
	    $headdata['flash_message'] = get_flashmessage();
	    $data['header'] = $this->load->view('header', $headdata, true);
	    $data['footer'] = $this->load->view('footer', '', true);
	    $this->load->view('listing/index', $data);
	}
 
	/**
	 * Shows the postlisting form
	 *
	 */
	function postlisting()
	{
	    $data = array();
	    $this->load->model('location_model');
	    $this->load->model('city_model');
	    $this->load->model('country_model');
	    $this->load->model('state_model');
	    $this->load->model('trantypes_model');
	    $this->load->model('propertytypes_model');
	    $this->load->model('pricerange_model');
 
	    $data['locations'] = $this->location_model->get_locations();
	    $data['cities'] = $this->city_model->get_cities();
	    $data['countries'] = $this->country_model->get_countries();
	    $data['states'] = $this->state_model->get_states();
	    $data['priceranges'] = $this->pricerange_model->get_priceranges();
	    $data['trantypes'] = $this->trantypes_model->get_trantypes();
	    $data['propertytypes'] = $this->propertytypes_model->get_propertytypes();
 
	    $headdata = array();
	    $headdata['flash_message'] = get_flashmessage();
 
	    $data['header'] = $this->load->view('header', $headdata, true);
	    $data['footer'] = $this->load->view('footer', '', true);
	    $this->load->view('listing/postlisting_form.php', $data);
	}
 
	/**
	 * postlisting action
	 *
	 */
	public function postlisting_action()
	{
	    $this->load->model('listing_model');
	    $this->load->model('photos_model');
 
	    $data = array();
	    $photo = array();
	    try {
    	    if (isset($_POST)) {
                if($_FILES['userfile']['size'] > 0) { 
 
                    $photo['filename'] = $_FILES['userfile']['name'];
                    $photo['filesize'] = $_FILES['userfile']['size'];
                    //$photo['filetype'] = $_FILES['userfile']['type'];
                    $photo['filetype'] = 'image/jpeg';
 
                    $tmpName  = $_FILES['userfile']['tmp_name'];
 
                    $fp      = fopen($tmpName, 'r');
                    $content = fread($fp, filesize($tmpName));
                    //$content = addslashes($content);
                    //$content = $content; //Code Igniter already has addslashes
                    fclose($fp);
 
                    if(!get_magic_quotes_gpc()) {
                        $photo['filename'] = addslashes($photo['filename']);
                    }
 
                    // get originalsize of image
                    $im = imagecreatefromstring($content);
                    $width = imagesx($im);
                    $height = imagesy($im);            
 
                    // Set thumbnail-height to 180 pixels
                    $imgh = 300;                                          
                    // calculate thumbnail-height from given width to maintain aspect ratio
                    $imgw = $width / $height * $imgh;                                          
                    // create new image using thumbnail-size
                    $thumb=imagecreatetruecolor($imgw,$imgh);                  
                    // copy original image to thumbnail
                    imagecopyresampled($thumb,$im,0,0,0,0,$imgw,$imgh,ImageSX($im),ImageSY($im)); //makes thumb
 
                    /*
                    imagejpeg($thumb, $photo['filename'], 80);  //imagejpeg($resampled, $fileName, $quality);            
                    $instr = fopen($photo['filename'],"rb");  //need to move this to a safe directory
                    $image = fread($instr,filesize($photo['filename']));
 
                    $photo['filecontent']  = $image;
                    */
                    //------
                    $thumbsdir = ini_get('upload_tmp_dir') ;
                    imagejpeg($thumb, $thumbsdir.$photo['filename'], 80);  //imagejpeg($resampled, $fileName, $quality);            
                    $instr = fopen($thumbsdir.$photo['filename'],"rb");  //need to move this to a safe directory
                    $image = fread($instr,filesize($thumbsdir.$photo['filename']));
 
                    $photo['filecontent']  = $image;
 
                    unlink($thumbsdir.$photo['filename']);
 
    	        }
 
    	        $_POST['listing']['user_id'] = $_SESSION['user_id'];
    	        $last_id = $this->listing_model->insert_listing($_POST['listing']);    
 
    	        if($_FILES['userfile']['size'] > 0) { 
    	            $photo['listing_id'] = $last_id;
                    $this->photos_model->upload_photo($photo);    
                    unset($photo);
    	        }
 
                add_flashmessage('Successfully saved data.');
                redirect('/listing/my_listings/');
            }
        } catch (Exception $e) {
            add_flashmessage($e->getMessage()); 
        }
    }
}

The Photos Controller: this controller is responsible for fetching the image from the database.

&lt; ?php
 
class Photos extends Controller {
 
	public function __construct()
	{
		parent::Controller();
	}
 
	public function getphoto($id,$thumbwidth = false)
	{
	    $this-&gt;load-&gt;model('photos_model');
 
	    try {
            $photo = $this-&gt;photos_model-&gt;fetch_photo('listing_id='.$id);    
 
            if($photo) {
                if (!$thumbwidth) {
                    header("Content-type: ".$photo['filetype']);
                    echo $photo['filecontent'];
                } else {
                    $this-&gt;load-&gt;helper('wenbertimage');
                    resize_this_image($photo['filecontent'], $photo['id'], $photo['filetype'], $thumbwidth);
                }
 
            } else {
                $photo = $this-&gt;photos_model-&gt;fetch_photo('filename="no_photo.gif"');
                header("Content-type: ".$photo['filetype']);
                echo $photo['filecontent'];
            }
 
	    } catch (Exception $e) {
	        echo $e-&gt;getMessage();
	    }
 
	}
 
	public function deletephoto($listing_id)
	{
	    if ($this-&gt;db-&gt;delete($this-&gt;_table, array('listing_id' =&gt; $listing_id))) {
            return true;
        } else {
            return false;
        }
	}
}
This entry was posted in General and tagged , , , . Bookmark the permalink.

8 Responses to Code Igniter: Resize image and save to database; Generate thumbnails

  1. cahva says:

    This is not needed:

    if (isset($_POST)) {

    $_POST is always set :)

  2. Wenbert says:

    thanks for noting this cahva. i must review the php basics ;) i will also be updating the code above. it contains some bugs and the uploaded images are not deleted.

  3. TomsB says:

    CodeIgniter has File Uploader Class and Image Manipulation Class.
    http://codeigniter.com/user_guide/libraries/file_uploading.html
    http://codeigniter.com/user_guide/libraries/image_lib.html

    No need to code these things yourself..
    I suggest reading User Guide from beginning to EOF. It took me about 20 hours to read guide and start to work with the best MVC and CodeIgniter coding principles.

  4. Wenbert says:

    Thanks for your inputs TomsB. :)

  5. Pingback: Recent Links Tagged With "thumbnails" - JabberTags

  6. good says:

    i have a bettr code you can mail me

  7. Thanks for this idea! By the way, the latest CI release already has a class to manipulate image uploads.

  8. Wenbert says:

    Thanks Brando! I haven’t checked out Code Igniter in a lonngggg time. Appreciate the update ;)

Leave a Reply to TomsB Cancel reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>