Code Igniter: Resize image and save to database; Generate thumbnails
Filed Under (General) by Wenbert on 13-08-2008
Tagged Under : Code Igniter, PHP, resize image, 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.
< ?php class Photos extends Controller { public function __construct() { parent::Controller(); } public function getphoto($id,$thumbwidth = false) { $this->load->model('photos_model'); try { $photo = $this->photos_model->fetch_photo('listing_id='.$id); if($photo) { if (!$thumbwidth) { header("Content-type: ".$photo['filetype']); echo $photo['filecontent']; } else { $this->load->helper('wenbertimage'); resize_this_image($photo['filecontent'], $photo['id'], $photo['filetype'], $thumbwidth); } } else { $photo = $this->photos_model->fetch_photo('filename="no_photo.gif"'); header("Content-type: ".$photo['filetype']); echo $photo['filecontent']; } } catch (Exception $e) { echo $e->getMessage(); } } public function deletephoto($listing_id) { if ($this->db->delete($this->_table, array('listing_id' => $listing_id))) { return true; } else { return false; } } }
Related posts:
- Why I hate Code Igniter (and why ZF FTW!) Here is a snippet from my code… public function transaction($company_var='',...
- Object-oriented programming PHP 5 Tutorial For those who are not familiar with PHP5 OOP, I...
- Zend Framework: View File downloaded as Excel File This is basically a back-up post from my previous posts...
- Zend Framework Tutorial: A Fully Customized Form Using Zend_Form and Decorators (UPDATED now using Tables) This tutorial is derived from this post. So I suggest...
- HTML Table to Excel File Tutorial Here is a tutorial on how to export something from...
Related posts brought to you by Yet Another Related Posts Plugin.

This is not needed:
if (isset($_POST)) {
$_POST is always set
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.
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.
Thanks for your inputs TomsB.
[…] 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 […]
i have a bettr code you can mail me