Speed up image rendering script
Posted: Mon Mar 10, 2008 4:42 pm
I have a controller in my app that is used to render an image based on input from the user. Basically it accepts a unique key, looks in the database to see if the image exists, and if so, reads it to the browser. If it doesn't exist, it renders an image that says "No Image Available" and issues a 404. It also allows you to request a thumbnail. If you do, it will check to see if one already exists, and if not, it will create one from the large image and output it. If an thumb already exists, it simply outputs it.
When I call a page that renders 15 or 20 images, it takes a while for all of them to render. Longer than if they were just images. My question is how do I speed this up? Any insight is helpful. Thanks, yo!
Code: Select all
<?php
class ImagesController extends AppController {
var $name = 'Images';
var $uses = array('Image','Home','Rv');
/**
* Outputs an image to the browser if one can be found, otherwise it issues a 404
*/
function view($id = null) {
if ($image = $this->Image->read(null, $id)) {
$this->__display($image['Image']['path'], $image['Image']['mime_type'], $image['Image']['size']);
} else {
header("HTTP/1.0 404 Not Found");
$this->__display(WWW_ROOT . 'img' . DS . 'not-available.png', 'image/png');
}
exit;
}
/**
* Output a thumbnail of a big image
* @todo Issue a 404, but output a No Image image
*/
function thumb($id) {
if ($image = $this->Image->read(null, $id)) {
$parts = pathinfo($image['Image']['path']);
$imagename = WWW_ROOT . 'img' . DS . 'uploads' . DS . 'homes' . DS . 'thumbs' . DS . $parts['basename'];
// if there is not a thumbnail for this image, create one
if(!file_exists($imagename)) {
$img = imagecreatefromjpeg($image['Image']['path']);
$height = 157;
$width = 210;
$rs_image = imagecreatetruecolor($width, $height);
imagecopyresampled($rs_image, $img, 0, 0, 0, 0, $width, $height, 400, 300);
imagejpeg($rs_image, $imagename, 100);
}
Configure::write('debug', 0);
header("HTTP/1.0 200 OK");
header(sprintf("Content-type: %s", $image['Image']['mime_type']));
header(sprintf("Content-length: %d", $image['Image']['size']));
readfile($imagename);
exit;
}
header("HTTP/1.0 404 Not Found");
$this->__display(WWW_ROOT . 'img' . DS . 'not-available-thumb.png', 'image/png');
exit;
}
/**
* Used for displaying an image by its path starting from uploads/
*/
function tmp($path, $type = "text/jpeg", $size = null) {
$this->__display(UPLOAD_DIR . $path, $type, $size);
}
function __display($path, $type = null, $size = null) {
Configure::write('debug', 0);
if (!$type) $type = "text/jpeg"; // best guess
if (!$size) $size = filesize($path);
//header("HTTP/1.0 200 OK"); // removed because I want to be able to issue a 404 and still show an image (a 404 one)
header(sprintf("Content-type: %s", $type));
header(sprintf("Content-length: %d", $size));
readfile($path);
exit;
}
}