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

Posted on: Aug 13, 2008 by wenbert

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;
        }
	}
}

Subscribe to comments Comment | Trackback |
Post Tags: , , ,

Browse Timeline


Comments ( 6 )

[...] public links >> thumbnails Code Igniter: Resize image and save to database; Generate thumbnails Saved by dot on Sun 26-10-2008 Access Your Favorite Sites Through Thumbnails: Fast Dial Saved by [...]

Recent Links Tagged With "thumbnails" - JabberTags added these pithy words on Oct 27 08 at 5:19 PM

This is not needed:

if (isset($_POST)) {

$_POST is always set :)

cahva added these pithy words on Sep 07 08 at 12:12 AM

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.

Wenbert added these pithy words on Sep 07 08 at 2:17 AM

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.

TomsB added these pithy words on Sep 10 08 at 10:29 PM

Thanks for your inputs TomsB. :)

Wenbert added these pithy words on Sep 11 08 at 9:06 AM

i have a bettr code you can mail me

good added these pithy words on Nov 28 08 at 4:30 PM

Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">


© Copyright 2007 eKini Web Developer Blog . Thanks for visiting!