CodeIgniter Forums
store and view image from a database sql string - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: store and view image from a database sql string (/showthread.php?tid=24323)



store and view image from a database sql string - El Forum - 11-06-2009

[eluser]davidino86[/eluser]
hi,

i'd like to know the best way to store a image in a varbinary(max) SQL field with a function in php using the support of CI file upload class.

once uploaded and saved into DB ho can decode and show the image

my functions are:

Model:
Code:
<?php

Class Image_model extends Model
{
    function image_model()
    {
        parent::Model();

            /*function is_base64_encoded($data)
                {
                    if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $data)) {
                      
                        return TRUE;
                    } else {
                        
                        return FALSE;
                    }
                }*/
    }
    
    function blob_upload()
    {

     if (!empty($_FILES['image']['name']))

     {
        //Get File Data Info
        $uploads = array($this->upload->data());

        $this->load->library('image_lib');

            //Move Files To User Folder
            foreach($uploads as $key[] => $value)
            {

            $ext= $value['file_ext'];
            $filesize = $value['file_size'];
            $timestamp = time();
            $data = pg_escape_bytea(file_get_contents($_FILES['image']['tmp_name']));


            /*
            * Add Pic Info To Database for MySQL
            *
            * $this->db->set('ext', $ext);
            * $this->db->set('size', $filesize);
            * $this->db->set('image', CONVERT(varbinary(MAX),$data));
            *
                */
  

           //QUERY FOR MSSQL
           $query = "INSERT INTO images (ext, size, image) VALUES ('$ext', $filesize, CONVERT(varbinary(MAX),'$data'))";

            /*
            * HOW TO EXECUTE THE QUERY:
            *
            * For MSSQL:
            * $this->db->query($query)
            *
            * For MySQL:
            * $this->db->insert('images')
            *
             */


            if($this->db->query($query)){

                $last_id = $this->db->insert_id();
                
                 echo $this->getImage($last_id);
                     //Response at Success

                }else{

                    echo 'error';
                   //Response at error
               }
            }
        }
    }

    function str_hex($string){
        $hex='';
        for ($i=0; $i < strlen($string); $i++){
            $hex .= dechex(ord($string[$i]));
        }
        return $hex;
    }


   function hex_str($hex){
            $string='';
            for ($i=0; $i < strlen($hex)-1; $i+=2){
                $string .= chr(hexdec($hex[$i].$hex[$i+1]));
            }
            return $string;
        }

    function getImage($id)
    {

        $image = NULL;

        /*$this->db->select('image');
        $this->db->where('image_ID', $id);
        $query = $this->db->get('images');*/

        $sql = "SELECT CONVERT(varchar(MAX), 'image') as image  FROM  images WHERE image_id = '$id'";
        $query = $this->db->query($sql);
        
        if ($query->num_rows() > 0)
        {
            $obj_image = $query->row();
        }
        return $obj_image->image;
    
    }


}

?&gt;

Controller:
Code:
&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Upload extends Controller {
    
    function Upload()
    {
        parent::Controller();
        $this->load->helper(array('form', 'url'));
        //Load Model
        $this->load->model('image_model');



    }
    
    function doUpload ()
    {
        
        $config['upload_path'] = 'uploads/'; //where
        $config['allowed_types'] = 'gif|jpg|png'; //format allowed
        $config['max_size']    = '2048'; //2 mega


        $this->load->library('upload');
        
        //foreach for multiply Upload
        foreach($_FILES as $key => $value)
        {

                $this->upload->initialize($config);


                if ( !$this->upload->do_upload($key))
                {
                    //PARSE ERRORS
                    $error = array('error' => $this->upload->display_errors());

                            //var_dump($error);
                            $msg = $this->upload->display_errors('<p>', '</p>');
                            echo 'errore: '.$msg;
                            

                }
                else
                {
                    //CALL THE MODEL METHOD FOR UPLOAD IMAGE/S
                    $this->image_model->blob_upload();

                }


        }
    }

    function displayImage()
        {

            //Retrieve image id from the URI
            $imageid = $this->uri->segment(3);
            //Initialize the images model
            $this->load->model("image_model", 'image');
            //Call the model's getImage function passing the image id
            $image = $this->image_model->getImage($imageid);
            if (!is_null($image)) {
                //If we get a valid value back, send header and image to browser.
                
                //$decode_image = $this->image_model->hex_str($image);

                //$created_image = imagecreatefromstring($image);
                //imagejpeg($created_image);
               // header('Content-Type: image/png');
                //print($created_image);

                header ('Content-Type: image/jpg');
                imagejpeg(imagecreatefromstring($image), null,100);
            }
        }
}
?&gt;


and the view for the image is

Code:
<img src="&lt;?=base_url()?&gt;upload/displayImage/18" alt="immagine caricata"/>

18 is ID,

thanks


store and view image from a database sql string - El Forum - 11-09-2009

[eluser]davidino86[/eluser]
up