Welcome Guest, Not a member yet? Register   Sign In
Reading an image from a database..
#1

[eluser]Unknown[/eluser]
I was already successful in inserting an image file to a database using the following code:

Code:
//Controller
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size']    = '100';
$config['max_width']  = '1024';
$config['max_height']  = '768';
                
$this->load->library('upload', $config);
        
if (!$this->upload->do_upload()){
    echo 'error uploading file!';
}else{
    echo 'success uploading file!';
    
    //Insert file to database.
    $file_info = $this->upload->data();
    $file_name = $file_info['full_path'];                
    $image_file = addslashes(fread(fopen($file_name, "r"), filesize($file_name)));    
    $this->dbc->img_to_db($image_file);
}

//Model
//I only have two fields in my images table, id and image
function img_to_db($image_file){
    $sql = "INSERT INTO images (image) VALUES (?)";
    $query = $this->db->query($sql, array($image_file));
}

When I tried to retrieve the image, using this code:

Code:
//View
<img src="&lt;? echo base_url(); ?&gt;view_img" />

//View_img Controller
function index(){
    header("Content-type: image/jpeg"); //I tried image/jpg, still didn't work.
    $image_file = $this->dbc->get_img_from_db(1); //Fixed value for now, just to test it
    echo $image_file->image; //Print or echo?
}

//Model
function get_img_from_db($image_id = 1){
    $sql = "SELECT image FROM images WHERE id = ?";
    $query = $this->db->query($sql, array($image_id));
    return $query->row();
}

..all I get is a broken image icon. Is there something wrong with what I am doing? If I removed the call to the header function in the controller, I was able to see the weird characters, which I assume is the image in a format that can be stored in the database.


Messages In This Thread
Reading an image from a database.. - by El Forum - 09-23-2009, 10:11 PM
Reading an image from a database.. - by El Forum - 09-23-2009, 10:35 PM
Reading an image from a database.. - by El Forum - 09-24-2009, 12:01 AM



Theme © iAndrew 2016 - Forum software by © MyBB