Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Resize an image on the fly with PHP and cache it (like Drupal's ImageCache)

This script takes an image and resizes it to the given dimensions, then saves that version on the filesystem so Apache can serve it directly in the future.

Inspired by Drupal's ImageCache module and a blog post by Sumit Birla, but written from scratch.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([a-z]+)/([^/]*)$ resize.php?size=$1&file=$2
<?php
// Resize images on-the-fly and then cache them
// Very similar to the imagecache module in Drupal
// by Dave Miller
chdir(dirname(__FILE__));
$size = $_GET['size'];
$file = $_GET['file'];
// Check the size is valid
switch ($size) {
case 'image':
$thumbWidth = 210;
$thumbHeight = 104;
break;
case 'text':
$thumbWidth = 55;
$thumbHeight = 55;
break;
case 'photos':
$thumbWidth = 184;
$thumbHeight = null;
break;
default:
die('Invalid image size');
}
// Check the filename is safe & check file type
if (preg_match('#^[a-z0-9\.]+\.(jpg|jpeg|png)$#i', $file, $matches) && strpos($file, '..') === false) {
$extension = $matches[1];
} else {
die("Invalid filename: $file");
}
// Check the original file exists
$original = "originals/$file";
if (!is_file($original)) {
die('File doesn\'t exist');
}
// Make sure the directory exists
if (!is_dir($size)) {
mkdir($size);
if (!is_dir($size)) {
die('Cannot create directory');
}
chmod($size, 0777);
}
// Make sure the file doesn't exist already
$target = "$size/$file";
if (!file_exists($target)) {
// Make sure we have enough memory
ini_set('memory_limit', 128*1024*1024);
// Get the current size & file type
list($width, $height, $type) = getimagesize($original);
// Load the image
switch ($type) {
case IMAGETYPE_GIF:
$image = imagecreatefromgif($original);
break;
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($original);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($original);
break;
default:
die("Invalid image type (#{$type} = " . image_type_to_extension($type) . ")");
}
// Calculate height automatically if not given
if ($thumbHeight === null) {
$thumbHeight = round($height * $thumbWidth / $width);
}
// Ratio to resize by
$widthProportion = $thumbWidth / $width;
$heightProportion = $thumbHeight / $height;
$proportion = max($widthProportion, $heightProportion);
// Area of original image that will be used
$origWidth = floor($thumbWidth / $proportion);
$origHeight = floor($thumbHeight / $proportion);
// Co-ordinates of original image to use
$x1 = floor($width - $origWidth) / 2;
$y1 = floor($height - $origHeight) / 2;
// Resize the image
$thumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($thumbImage, $image, 0, 0, $x1, $y1, $thumbWidth, $thumbHeight, $origWidth, $origHeight);
// Save the new image
switch ($type)
{
case IMAGETYPE_GIF:
imagegif($thumbImage, $target);
break;
case IMAGETYPE_JPEG:
imagejpeg($thumbImage, $target, 90);
break;
case IMAGETYPE_PNG:
imagepng($thumbImage, $target);
break;
default:
throw new LogicException;
}
// Make sure it's writable
chmod($target, 0666);
// Close the files
imagedestroy($image);
imagedestroy($thumbImage);
}
// Send the file header
$data = getimagesize($original);
if (!$data) {
die("Cannot get mime type");
} else {
header('Content-Type: ' . $data['mime']);
}
// Send the file to the browser
readfile($target);
@smitione

This comment has been minimized.

Show comment
Hide comment
@smitione

smitione Oct 12, 2014

Can you post an exaple of how to use it int a <img src""> case?

Can you post an exaple of how to use it int a <img src""> case?

@davejamesmiller

This comment has been minimized.

Show comment
Hide comment
@davejamesmiller

davejamesmiller Mar 25, 2015

Example:

<img src="/images/photo/filename.jpg" />

Where the original (large) image is stored in /images/originals/filename.jpg.

This will generate a 184px-wide resized image and scale the height automatically.

Owner

davejamesmiller commented Mar 25, 2015

Example:

<img src="/images/photo/filename.jpg" />

Where the original (large) image is stored in /images/originals/filename.jpg.

This will generate a 184px-wide resized image and scale the height automatically.

@thirdender

This comment has been minimized.

Show comment
Hide comment
@thirdender

thirdender Jun 22, 2015

Thanks for the great script! I needed the width passed as a query string. My URLs looked something like http://domain/images/backgrounds/image.jpg?size=1400. I used the following .htaccess to call the script:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ([^/]*)$ resize.php?file=$1 [QSA,L]

Thanks for the great script! I needed the width passed as a query string. My URLs looked something like http://domain/images/backgrounds/image.jpg?size=1400. I used the following .htaccess to call the script:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ([^/]*)$ resize.php?file=$1 [QSA,L]
@sanjeev81

This comment has been minimized.

Show comment
Hide comment
@sanjeev81

sanjeev81 Jul 23, 2015

What the helll ?

What the helll ?

@sanjeev81

This comment has been minimized.

Show comment
Hide comment
@sanjeev81

sanjeev81 Jul 23, 2015

You didnt post how to use you idniojfnvmb

You didnt post how to use you idniojfnvmb

@rituraj83

This comment has been minimized.

Show comment
Hide comment
@rituraj83

rituraj83 Jul 14, 2016

I have tried this script and Works really good.
Below is the flow.
-> first put resize.php and .htaccess file somewhere on the root
-> Also created folder on same location with name 'originals'
-> Your image should be in 'originals' folder which you wanted to resize dynamically.
-> Now all done. Try to access image with this url '/resize.php?file=imagename.jpg&size=image'.

Thank you,
Ritesh Patel

I have tried this script and Works really good.
Below is the flow.
-> first put resize.php and .htaccess file somewhere on the root
-> Also created folder on same location with name 'originals'
-> Your image should be in 'originals' folder which you wanted to resize dynamically.
-> Now all done. Try to access image with this url '/resize.php?file=imagename.jpg&size=image'.

Thank you,
Ritesh Patel

@ketanrf

This comment has been minimized.

Show comment
Hide comment
@ketanrf

ketanrf Sep 9, 2016

hi all

please help me

i am .net developer so .htaccess file can't work on windows server

please convert ..htaccess to web.confing code so i can use resize.php in my project

ketanrf commented Sep 9, 2016

hi all

please help me

i am .net developer so .htaccess file can't work on windows server

please convert ..htaccess to web.confing code so i can use resize.php in my project

@vambroise

This comment has been minimized.

Show comment
Hide comment
@vambroise

vambroise Dec 18, 2017

Hello,
Thanks for this gist.

I modified the regex slightly to allow filenames containing "_" or "-" (which is quite frequent).

if (preg_match('#^[a-z0-9_\-\.]+(@2x)?\.(jpg|jpeg|png)$#i', $file, $matches) && strpos($file, '..') === false) {
  $retina = $matches[1];
  $extension = $matches[2];
} else {
  die("Invalid filename: $file");
}

vambroise commented Dec 18, 2017

Hello,
Thanks for this gist.

I modified the regex slightly to allow filenames containing "_" or "-" (which is quite frequent).

if (preg_match('#^[a-z0-9_\-\.]+(@2x)?\.(jpg|jpeg|png)$#i', $file, $matches) && strpos($file, '..') === false) {
  $retina = $matches[1];
  $extension = $matches[2];
} else {
  die("Invalid filename: $file");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment