Skip to content

Instantly share code, notes, and snippets.

@jam13
Last active April 25, 2016 09:22
Show Gist options
  • Select an option

  • Save jam13/a225ccde02522abc0bc70234aa5ab6a6 to your computer and use it in GitHub Desktop.

Select an option

Save jam13/a225ccde02522abc0bc70234aa5ab6a6 to your computer and use it in GitHub Desktop.
SilverStripe lorempixel

SilverStripe lorempixel

Requires SilverStripe 3.3 (may work with other 3.x versions)

Usage

/thumbs/100/100 - Random 100 pixel square image /thumbs/100/100/faces - Random image from the faces folder /thumbs/100/100/faces/bo - Image called bo (Title) from the faces folder

Notes

Works well through a reverse proxy (e.g. nginx) to reduce load. Requires addition of cachebusting suffix to get fresh (random) image.

---
Name: mysiteroutes
After: framework/routes#coreroutes
---
Director:
rules:
'thumbs/$x!/$y!/$group/$filename': 'ThumbController'
<?php
class ThumbController extends Controller {
private static $allowed_actions = array(
'index'
);
public function index(SS_HTTPRequest $request) {
$x = (int)$this->getRequest()->param('x');
$y = (int)$this->getRequest()->param('y');
if(!$x || !$y) {
return $this->httpError(404, '404 Not Found');
}
if($x > 1000 || $y > 1000) {
return $this->httpError(400, '400 Bad Request');
}
$group = $this->getRequest()->param('group');
$filename = $this->getRequest()->param('filename');
$images = Image::get();
if($group) {
$folder = Folder::find($group);
$images = $images->filter(array(
'ParentID' => $folder->ID
));
}
if($filename) {
$images = $images->addFilter(array(
'Title' => $filename
));
}
if($images->count() < 1) {
return $this->httpError(404, '404 Not Found');
}
$image = $images->sort('RAND()')->first();
$thumb = $image->Fill($x,$y);
$path = $thumb->getFullPath();
header('Content-Length: ' . $thumb->getAbsoluteSize());
header('Content-Type: ' . HTTP::get_mime_type($thumb->getRelativePath()));
header('Content-Transfer-Encoding: binary');
while (ob_get_level() > 0) {
ob_end_flush();
}
session_write_close();
readfile($path);
die();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment