Is there a way to have a Codeigniter controller return an image? Is there a way to have a Codeigniter controller return an image? codeigniter codeigniter

Is there a way to have a Codeigniter controller return an image?


sure you can, use this instead of $this->load->view()

$filename="/path/to/file.jpg"; //<-- specify the image  fileif(file_exists($filename)){   $mime = mime_content_type($filename); //<-- detect file type  header('Content-Length: '.filesize($filename)); //<-- sends filesize header  header("Content-Type: $mime"); //<-- send mime-type header  header('Content-Disposition: inline; filename="'.$filename.'";'); //<-- sends filename header  readfile($filename); //<--reads and outputs the file onto the output buffer  exit(); // or die()}


This is not intended as One-upmanship, but pǝlɐɥʞ's suggestion is a pure PHP implementation that is not all that re-usable. You wanted to use the syntax $this->load->image('images/gorilla.png') so here is how you can.

Create /application/libraries/MY_Loader.php

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');/** * Loader Class * * Loads views and files * * @package     CodeIgniter * @subpackage  Libraries * @author      Phil Sturgeon * @category    Loader * @link        http://codeigniter.com/user_guide/libraries/loader.html */class MY_Loader extends CI_Loader {    function image($file_path, $mime_type_or_return = 'image/png')    {        $this->helper('file');        $image_content = read_file($file_path);        // Image was not found        if($image_content === FALSE)        {            show_error('Image "'.$file_path.'" could not be found.');            return FALSE;        }        // Return the image or output it?        if($mime_type_or_return === TRUE)        {            return $image_content;        }        header('Content-Length: '.strlen($image_content)); // sends filesize header        header('Content-Type: '.$mime_type_or_return); // send mime-type header        header('Content-Disposition: inline; filename="'.basename($file_path).'";'); // sends filename header        exit($image_content); // reads and outputs the file onto the output buffer    }

There are a few ways you can use this:

Basic output (default is jpeg)

$this->load->image('/path/to/images/gorilla.png');

Send mime-type to use other image types

$this->load->image('/path/to/images/gorilla.jpg', 'image/jpeg');

Return the image

$image = $this->load->image('/path/to/images/gorilla.php', TRUE);

Just like $this->load->view, the 3rd parameter being set to TRUE means it will return instead of directly outputting.

Hope this helps :-)


An easier way with automatic mime-type.

$this->load->helper('file');$image_path = '/path/to/image/file';$this->output->set_content_type(get_mime_by_extension($image_path));$this->output->set_output(file_get_contents($image_path));