How to generate image on the fly with codeIgniter

This post is talking about how to generate image on the fly with codeigniter. This is the basic code and sure you can improve it as you far as you need, All we need is only 1 controller and 1 view

1. Controller

Create controller and named it “preview”, we also need function in it to call the image class. See the script below


<?php

class preview extends Controller {

function preview()
{
parent::Controller();
$this->load->helper('url');
}

function index($height='50',$width='50')
{

// we will need to pass the height and with of the image
$arr_data['height']    =    $height;
$arr_data['width']    =    $width;
$this->load->view('preview', $arr_data);
}

function get_photo($height,$width){
$path = [ absolute path to your image ex : /public-html/dock/image.jpg ];
$this->load->library('image_lib');
$imageinit['image_library']     = 'gd2';
$imageinit['quality']            = '90%'; // set quality
$imageinit['dynamic_output']    = true;     // set to true to generate it dynamically
$imageinit['source_image']         = $path;
$imageinit['maintain_ratio']     = false;
$imageinit['width']             = $width;
$imageinit['height']             = $height;
$this->image_lib->initialize($imageinit);
if(!$this->image_lib->resize()){
echo $this->image_lib->display_errors(); // print error if it fails
}
}
}

?>

“get_photo” function is where we will generate the image dynamically. We call this function in <img> html tag in “view” file.

2. View

Here is the view code where we will call “get_photo” function


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Code Igniter : Image on the fly</title>
</head>
<body>
<img src="<?php echo base_url().'index.php/preview/get_photo/'.$height.'/'.$width.'' ?>" title="image on the fly" alt="image on the fly" />
</body>
</html>

That’s it

  • Share/Bookmark

No Responses to “How to generate image on the fly with codeIgniter”

Leave a Reply